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

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

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

一、效果展示

二、代码实现

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



相关推荐

C/C++语言的引用与指针比较说明_c++语言中的引用类型与指针的不同之处

在C/C++编程中,引用与指针是实现数据间接访问的核心工具,二者均能优化参数传递效率、支持复杂数据操作,但在本质、语法与使用场景上存在显著差异。混淆二者易导致内存泄漏、悬空访问等严重问题。一、基础概念...

再也不点来点去了!用这几条命令,文件管理快10倍!(第003课)

大家好,今天给大家介绍如何用命令提示符(CMD)来管理你的文件!听起来可能有点高大上,但其实非常简单,而且一旦学会了,效率超高,特别适合那些喜欢快速搞定事情的朋友。那我们就从基础的操作开始,教你怎...

C/C++逆向分析实战:变量存储与安全防护全攻略

在软件开发的世界里,C/C++语言因其卓越的性能和强大的功能而备受开发者青睐。然而,随着技术的不断进步,逆向工程也逐渐成为一种常见的攻击手段。今天,我们将深入探讨C/C++中不同类型的变量在逆向分析中...

简单的python-核心篇-命名空间与作用域

命名空间是变量名到对象的映射,作用域决定了变量在哪些地方可以被访问。Python使用LEGB规则来确定变量的作用域。#全局命名空间global_var="我是全局变量"de...

Jmeter参数化:User Defined Variables-用户定义的变量

位置:如下图,Add--ConfigElement--UserDefinedVariables作用:定义你所需要的参数,比如IP使用:${IP}使用的场景:比如域名什么的,可以提出来参数化,以...

PySnooper:实时看行号 / 变量值,摆脱 print 的函数调试工具

开篇:调试也能这么爽?你是不是和我一样,天天跟print()打交道,一行行地往代码里塞调试信息?有时候加完又删,删完又忘,简直要疯掉!要是能像Bash的set-x那样,一键打开“观察模式...

组态王入门之建立变量、变量连接、弹窗设计

一、建立变量(1)打开组态王软件,左侧找到变量的菜单(2)点击菜单(3)找到变量组,再新建一个二级变量组(4)在新建的泵站分配井阀门中建立变量因是新的PLC需要先建立一个驱动找到西门子àS7-200(...

为什么老外还是喜欢在官方网站上买东西?

今天看了一下一些品牌的官方网站,从浏览到购买支付流程都是很顺畅的,而一些国外的品牌在国内的网站好多都是引导至微信小程序或是淘宝京东上面去购买。国外的品牌官网好像都很简单,比如一些卖服装的类的,基本就是...

支撑京东小程序的开发框架 「Taro」,免费学习

转载自:性能与架构公众号Taro简介现在小程序平台太多了,例如:微信小程序QQ小程序支付宝小程序百度小程序字节跳动小程序针对他们都各自开发一套的话开发成本就太高了。如果写一套代码,就能开发出适配这么...

比较工具大集合_比较各种工具在编辑使用pl/sql程序过程中的优劣

现在各大网络平台流传着大量的文件夹和文件比较工具,其中不乏滥竽充数的,软件使用不够流畅,对比功能不够强大。很多人要么找不到合适的工具,要么在寻找过程中浪费了大量的时间,下面小编就和大家分享一些个人私藏...

关于前端开发的20篇文档与指南_前端开发文档怎么编写

相信在2015年很多这个行业的人都会有这样的两种感受:真的不知所措,这个行业到底有多少东西需要去学习;渴望更多,并迫不及待的为接下来的学习寻求一些思想方向。第一个来自于我们的个人感受,而第二个则是纯粹...

成为一名合格的前端架构师,前端知识技能与项目实战教学

一、教程描述本套前端架构师教程,大小35.94G,共有672个文件。二、教程目录01.node介绍和环境配置(共6课时)02.ES6语法(共5课时)03.node基础(共29课时)04.Express...

吃透 Vue 项目开发实践|16个方面深入前端工程化开发技巧【下】

前言前面两篇文章总结了Vue开发的大部分技巧和内容,最后一篇文章来对它进行一个收尾这篇文章我们来谈谈一些Vue理解和实践要求高一点的问题首先是生命周期这一块内容,随着实践越多它的意义越大,理解...

在w3cschool上学完html、css后要怎么提升

原标题:在w3cschool学完html,css,javascript,jquery以后,还是不会做前端怎么办?w3cschool是一个非盈利性的在线技术学习网站,提供按W3C标准编写的基础教程。完整...

从0到1无比流畅的React入门教程_react教程推荐

React是什么简介用于构建Web和原生交互界面的库React用组件创建用户界面通俗来讲:==是一个将数据渲染为HTML视图的开源JS库==其他信息Facebook开发,并且开源为什么使用R...