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

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

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

一、效果展示

二、代码实现

引用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实现图片、视频上传



相关推荐

Python入门学习记录之一:变量_python怎么用变量

写这个,主要是对自己学习python知识的一个总结,也是加深自己的印象。变量(英文:variable),也叫标识符。在python中,变量的命名规则有以下三点:>变量名只能包含字母、数字和下划线...

python变量命名规则——来自小白的总结

python是一个动态编译类编程语言,所以程序在运行前不需要如C语言的先行编译动作,因此也只有在程序运行过程中才能发现程序的问题。基于此,python的变量就有一定的命名规范。python作为当前热门...

Python入门学习教程:第 2 章 变量与数据类型

2.1什么是变量?在编程中,变量就像一个存放数据的容器,它可以存储各种信息,并且这些信息可以被读取和修改。想象一下,变量就如同我们生活中的盒子,你可以把东西放进去,也可以随时拿出来看看,甚至可以换成...

绘制学术论文中的“三线表”具体指导

在科研过程中,大家用到最多的可能就是“三线表”。“三线表”,一般主要由三条横线构成,当然在变量名栏里也可以拆分单元格,出现更多的线。更重要的是,“三线表”也是一种数据记录规范,以“三线表”形式记录的数...

Python基础语法知识--变量和数据类型

学习Python中的变量和数据类型至关重要,因为它们构成了Python编程的基石。以下是帮助您了解Python中的变量和数据类型的分步指南:1.变量:变量在Python中用于存储数据值。它们充...

一文搞懂 Python 中的所有标点符号

反引号`无任何作用。传说Python3中它被移除是因为和单引号字符'太相似。波浪号~(按位取反符号)~被称为取反或补码运算符。它放在我们想要取反的对象前面。如果放在一个整数n...

Python变量类型和运算符_python中变量的含义

别再被小名词坑哭了:Python新手常犯的那些隐蔽错误,我用同事的真实bug拆给你看我记得有一次和同事张姐一起追查一个看似随机崩溃的脚本,最后发现罪魁祸首竟然是她把变量命名成了list。说实话...

从零开始:深入剖析 Spring Boot3 中配置文件的加载顺序

在当今的互联网软件开发领域,SpringBoot无疑是最为热门和广泛应用的框架之一。它以其强大的功能、便捷的开发体验,极大地提升了开发效率,成为众多开发者构建Web应用程序的首选。而在Spr...

Python中下划线 ‘_’ 的用法,你知道几种

Python中下划线()是一个有特殊含义和用途的符号,它可以用来表示以下几种情况:1在解释器中,下划线(_)表示上一个表达式的值,可以用来进行快速计算或测试。例如:>>>2+...

解锁Shell编程:变量_shell $变量

引言:开启Shell编程大门Shell作为用户与Linux内核之间的桥梁,为我们提供了强大的命令行交互方式。它不仅能执行简单的文件操作、进程管理,还能通过编写脚本实现复杂的自动化任务。无论是...

一文学会Python的变量命名规则!_python的变量命名有哪些要求

目录1.变量的命名原则3.内置函数尽量不要做变量4.删除变量和垃圾回收机制5.结语1.变量的命名原则①由英文字母、_(下划线)、或中文开头②变量名称只能由英文字母、数字、下画线或中文字所组成。③英文字...

更可靠的Rust-语法篇-区分语句/表达式,略览if/loop/while/for

src/main.rs://函数定义fnadd(a:i32,b:i32)->i32{a+b//末尾表达式}fnmain(){leta:i3...

C++第五课:变量的命名规则_c++中变量的命名规则

变量的命名不是想怎么起就怎么起的,而是有一套固定的规则的。具体规则:1.名字要合法:变量名必须是由字母、数字或下划线组成。例如:a,a1,a_1。2.开头不能是数字。例如:可以a1,但不能起1a。3....

Rust编程-核心篇-不安全编程_rust安全性

Unsafe的必要性Rust的所有权系统和类型系统为我们提供了强大的安全保障,但在某些情况下,我们需要突破这些限制来:与C代码交互实现底层系统编程优化性能关键代码实现某些编译器无法验证的安全操作Rus...

探秘 Python 内存管理:背后的神奇机制

在编程的世界里,内存管理就如同幕后的精密操控者,确保程序的高效运行。Python作为一种广泛使用的编程语言,其内存管理机制既巧妙又复杂,为开发者们提供了便利的同时,也展现了强大的底层控制能力。一、P...