百度360必应搜狗淘宝本站头条
当前位置:网站首页 > 技术文章 > 正文

C#导出excel复杂表格(单元各合并)

zhezhongyun 2025-05-28 21:41 4 浏览

一、效果展示

二、代码实现

引用dll

using Aspose.Cells;

DataTable数据保存到Excel

/// <summary>
/// DataTable数据表保存至Excel (合并行报表)
/// </summary>
/// <param name="dt"></param>
/// <param name="filePath"></param>
/// <param name="excelParm"></param>
public static void ToExcel1(DataTable dt, string filePath, ExcelParm excelParm)
{
	string subTitle = string.Empty;




	//新建工作簿  
	Workbook wb = new Workbook();
	//新建工作表  
	Worksheet ws = wb.Worksheets[0];


	ws.Name = dt.TableName;


	int rowIndex = 3;
	int colIndex = 0;
	int colCount = dt.Columns.Count;
	int rowCount = dt.Rows.Count;


	ws.Cells.SetRowHeight(rowIndex, 25);//设置行高


	//创建样式
	Style style = wb.Styles[wb.Styles.Add()];//新增样式  
	style.HorizontalAlignment = TextAlignmentType.Center; //单元格内容的水平对齐方式文字居中
	style.Font.Name = "宋体"; //字体
	style.Font.IsBold = true; //设置粗体
	//style.Font.Color = Color.White;//设置字体颜色
	style.Font.Size = 10; //设置字体大小
	//style.ForegroundColor = Color.FromArgb(0, 196, 180); //背景色
	style.Pattern = BackgroundType.Solid;


	style.Borders[BorderType.TopBorder].LineStyle = CellBorderType.Thin;
	style.Borders[BorderType.TopBorder].Color = Color.Black;
	style.Borders[BorderType.BottomBorder].LineStyle = CellBorderType.Thin;
	style.Borders[BorderType.BottomBorder].Color = Color.Black;
	style.Borders[BorderType.LeftBorder].LineStyle = CellBorderType.Thin;
	style.Borders[BorderType.LeftBorder].Color = Color.Black;
	style.Borders[BorderType.RightBorder].LineStyle = CellBorderType.Thin;
	style.Borders[BorderType.RightBorder].Color = Color.Black;




	//列名的处理
	for (int i = 0; i < colCount; i++)
	{
		ws.Cells[rowIndex, colIndex].PutValue(dt.Columns[i].ColumnName);
		ws.Cells[rowIndex, colIndex].SetStyle(style);//给单元格关联样式
		colIndex++;
	}




	Style style2 = wb.Styles[wb.Styles.Add()];//新增样式
	style2.Font.Name = "宋体";//文字字体
	style2.Font.Size = 10;//文字大小 
	style2.ShrinkToFit = true;
	style2.VerticalAlignment = TextAlignmentType.Center;


	style2.Borders[BorderType.TopBorder].LineStyle = CellBorderType.Thin;
	style2.Borders[BorderType.TopBorder].Color = Color.Black;
	style2.Borders[BorderType.BottomBorder].LineStyle = CellBorderType.Thin;
	style2.Borders[BorderType.BottomBorder].Color = Color.Black;
	style2.Borders[BorderType.LeftBorder].LineStyle = CellBorderType.Thin;
	style2.Borders[BorderType.LeftBorder].Color = Color.Black;
	style2.Borders[BorderType.RightBorder].LineStyle = CellBorderType.Thin;
	style2.Borders[BorderType.RightBorder].Color = Color.Black;


	Style style3 = wb.Styles[wb.Styles.Add()];//组织标题样式
	style3.Font.Name = "宋体";//文字字体
	style3.Font.Size = 16;//文字大小 
	style3.HorizontalAlignment = TextAlignmentType.Center;
	ws.Cells.SetRowHeight(0, 25);//设置行高
	ws.Cells.Merge(0, 0, 1, dt.Columns.Count);
	ws.Cells[0, 0].PutValue(excelParm.OrganName);
	ws.Cells[0, 0].SetStyle(style3);


	Style style5 = wb.Styles[wb.Styles.Add()];//标题样式
	style5.Font.Name = "宋体";//文字字体
	style5.Font.IsBold = true; //设置粗体
	style5.Font.Size = 14;//文字大小 
	style5.HorizontalAlignment = TextAlignmentType.Center;
	ws.Cells.SetRowHeight(1, 25);//设置行高
	ws.Cells.Merge(1, 0, 1, dt.Columns.Count);
	ws.Cells[1, 0].PutValue(dt.TableName);
	ws.Cells[1, 0].SetStyle(style5);


	Style style4 = wb.Styles[wb.Styles.Add()];//新增查询条件标题样式
	style4.Font.Name = "宋体";//文字字体
	style4.Font.IsBold = true; //设置粗体
	style4.Font.Size = 10;//文字大小 
	ws.Cells.SetRowHeight(2, 25);//设置行高
	ws.Cells.Merge(2, 0, 1, dt.Columns.Count);
	ws.Cells[2, 0].PutValue(subTitle);
	ws.Cells[2, 0].SetStyle(style4);


	rowIndex++;


	for (int i = 0; i < rowCount; i++)
	{
		ws.Cells.SetRowHeight(rowIndex, 25);//设置行高
		colIndex = 0;
		for (int j = 0; j < colCount; j++)
		{
			ws.Cells[rowIndex, colIndex].PutValue(dt.Rows[i][j].ToString() == "" ? null : dt.Rows[i][j].ToString());
			style2.ForegroundColor = Color.White;
			style2.Pattern = BackgroundType.Solid;
			ws.Cells[rowIndex, colIndex].SetStyle(style2);//给单元格关联样式
			colIndex++;
		}
		rowIndex++;
	}


	//设置所有列为自适应列宽 
	ws.AutoFitColumns();


	for (int col = 0; col < colCount; col++)
	{
		ws.Cells.SetColumnWidthPixel(col, ws.Cells.GetColumnWidthPixel(col) + 20);
	}




	#region 合并单元格
	int mergeDateStart = 4;
	int mergeDate = 1;


	int mergeAreaStart = 4;
	int mergeArea = 1;
	for (var i = 0; i < dt.Rows.Count; i++)
	{
		if (i + 1 < dt.Rows.Count)
		{
			//日期
			if (dt.Rows[i]["日期"].ToString() != dt.Rows[i + 1]["日期"].ToString())
			{
				ws.Cells.Merge(mergeDateStart, 0, mergeDate, 1);
				mergeDateStart += mergeDate;
				mergeDate = 1;
			}
			else
			{
				mergeDate++;
			}


			//区域
			if (dt.Rows[i]["区域"].ToString() != dt.Rows[i + 1]["区域"].ToString())
			{
				ws.Cells.Merge(mergeAreaStart, 1, mergeArea, 1);
				mergeAreaStart += mergeArea;
				mergeArea = 1;
			}
			else
			{
				mergeArea++;
			}
		}
		else
		{
			//日期
			ws.Cells.Merge(mergeDateStart, 0, mergeDate, 1);
			//区域
			ws.Cells.Merge(mergeAreaStart, 1, mergeArea, 1);
		}
	}
	#endregion




	string fullUpLoadPath = HttpContext.Current.Server.MapPath("~/UpLoad/Excel/");
	//检查本地上传的物理路径是否存在,不存在则创建
	if (!System.IO.Directory.Exists(fullUpLoadPath))
	{
		System.IO.Directory.CreateDirectory(fullUpLoadPath);
	}


	filePath = GetMapPath(filePath);
	if (System.IO.File.Exists(filePath))
		System.IO.File.Delete(filePath);
	System.IO.FileStream fs = System.IO.File.Create(filePath);
	fs.Close();
	wb.Save(filePath);
}

以上就完成了,快去试试吧。

  • C#实现西门子S7-1200、200 SMART PLC之间通信
  • C#连接FTP实现文件上传下载
  • C#实现MQTT通讯
  • C#实现串口通讯
  • C#实现WebSocket服务和通讯
  • C#实现UDP通讯
  • C#实现TCP通讯
  • C#调用WebApi请求常用的两种方式
  • C# .NET MVC实现图片、视频上传



相关推荐

「教程」5 分钟带你入门 kivy

原创:星安果AirPythonkivy语言通过编写界面UI,然后利用Python定义一些业务逻辑,可以移植很多功能模块到移动端直接执行。下面对kivy常见用法做一个汇总。1、什么是...

【HarmonyOS Next之旅】基于ArkTS开发(二) -> UI开发三

目录1->绘制图形1.1->绘制基本几何图形1.2->绘制自定义几何图形2->添加动画效果2.1->animateTo实现闪屏动画2.2->...

Python设置excel表格格式,这3个属性6个模块,要表格好看

前言:通过前面两篇文章,我们用Python处理excel数据得到了结果并保存了文件。打开文件会发现,文件里表格是没有设置格式的,还需手动调整行高列宽等样式,很麻烦。其实,通过Python库模块,能轻松...

鸿蒙开发(三十三):Column

Column是一个沿垂直方向布局的容器。例如:@Entry@ComponentexportstructIndex{build(){Column(){Tex...

实战 | 如何制作数据报表并实现自动化?

本章给大家演示一下在实际工作中如何结合Pandas库和openpyxl库来自动化生成报表。假设我们现在有如图1所示的数据集。(图1)现在需要根据这份数据集来制作每天的日报情况,主要包含以下...

C# 给Word每一页设置不同图片水印

Word中设置水印时,可加载图片设置为水印效果,但通常添加水印效果时,会对所有页面都设置成统一效果,如果需要对每一页或者某个页面设置不同的水印效果,则可以参考本文中的方法。下面,将以C#代码为例,对W...

Inkscape 教程:创建棒球缝线效果

本教程将演示如何使用Inkscape中的PatternAlongPath路径效果来创建棒球上的缝线。基本原理是先创建一个代表单个缝线元素的图形(包括缝线本身和其下方的模拟孔洞),然后创建一...

ArkUI-Text/Span 详解

ArkUI-Text/Span详解@Entry@ComponentstructTextDemo{build(){Column({space:16}){Te...

【HarmonyOS Next之旅】兼容JS的类Web开发(五) -> Svg

目录1->基础知识1.1->创建Svg组件1.2->设置属性2->绘制图形3->绘制路径4->绘制文本4.1->文本4.2-&g...

Android常用布局总结之(LinearLayout、GridLayout等4种)

一、LinearLayout线性布局LinearLayout是一个视图组,用于使所有子视图在单个方向(垂直或水平)保持对齐。您可以使用android:orientation属性指定布局方向。a...

Excel vba常用语句

以下是常用的30个ExcelVBA语句:1.Range("A1").Value="HelloWorld"'将单元格A1的值设置为"Hello...

C#导出excel复杂表格(单元各合并)

一、效果展示二、代码实现引用dllusing Aspose.Cells;DataTable数据保存到Excel/// <summary>/// DataTa...

Excel-VBA代码,合并单元格

要求:合并第三列相同商品的单元格。vba合并单元格代码,代码运行如下。代码分享如下:Sub合并单元格()Dimi%'声明变量Application.DisplayAlerts=Fal...

MFC转QT:Qt高级特性 - 模型/视图架构

模型/视图架构概述Qt的模型/视图架构是一种设计模式实现,用于将数据存储与数据显示分离开来。这种设计与MFC的文档/视图架构有相似之处,但更加灵活和强大。它是Qt区别于MFC的最重要特性之一,能大幅提...

Excel单工作表拆分成多个工作表,掌握这个技能工作效率提升10倍

在我们的工作当中,常常会遇到这样的工作场景,我们需要将一个汇总的工作表按照某列的字段拆分为多个工作表。按照惯例,我们还是通过实际的一个例子来给大家进行形象的讲解吧。下面为某学校高一年级的成绩汇总表,我...