一、使用Microsoft.Office.Interop.Excel.DLL

  需要安装Office

  代码如下:

2 publicstaticboolExportExcel(System.Data.DataTable dt, stringpath)
3 {
4 boolsucceed =false;
5 if(dt !=null)
6 {
7 Microsoft.Office.Interop.Excel.Application xlApp =null;
8 try
9 {
10 xlApp =newMicrosoft.Office.Interop.Excel.ApplicationClass();
11 }
12 catch(Exception ex)
13 {
14 throwex;
15 }
16 
17 if(xlApp !=null)
18 {
19 try
20 {
21 Microsoft.Office.Interop.Excel.Workbook xlBook =xlApp.Workbooks.Add(true);
22 objectoMissing =System.Reflection.Missing.Value;
23 Microsoft.Office.Interop.Excel.Worksheet xlSheet =null;
24 
25 xlSheet =(Worksheet)xlBook.Worksheets[1];
26 xlSheet.Name =dt.TableName;
27 
28 introwIndex =1;
29 intcolIndex =1;
30 intcolCount =dt.Columns.Count;
31 introwCount =dt.Rows.Count;
32 
33 //列名的处理
34 for(inti =0; i <colCount; i++)
35 {
36 xlSheet.Cells[rowIndex, colIndex] =dt.Columns[i].ColumnName;
37 colIndex++;
38 }
39 //列名加粗显示
40 xlSheet.get_Range(xlSheet.Cells[rowIndex, 1], xlSheet.Cells[rowIndex, colCount]).Font.Bold =true;
41 xlSheet.get_Range(xlSheet.Cells[rowIndex, 1], xlSheet.Cells[rowCount +1, colCount]).Font.Name ="Arial";
42 xlSheet.get_Range(xlSheet.Cells[rowIndex, 1], xlSheet.Cells[rowCount +1, colCount]).Font.Size ="10";
43 rowIndex++;
44 
45 for(inti =0; i <rowCount; i++)
46 {
47 colIndex =1;
48 for(intj =0; j <colCount; j++)
49 {
50 xlSheet.Cells[rowIndex, colIndex] =dt.Rows[i][j].ToString();
51 colIndex++;
52 }
53 rowIndex++;
54 }
55 xlSheet.Cells.EntireColumn.AutoFit();
56 
57 xlApp.DisplayAlerts =false;
58 path =Path.GetFullPath(path);
59 xlBook.SaveCopyAs(path);
60 xlBook.Close(false, null, null);
61 xlApp.Workbooks.Close();
62 Marshal.ReleaseComObject(xlSheet);
63 Marshal.ReleaseComObject(xlBook);
64 xlBook =null;
65 succeed =true;
66 }
67 catch(Exception ex)
68 {
69 succeed =false;
70 }
71 finally
72 {
73 xlApp.Quit();
74 Marshal.ReleaseComObject(xlApp);
75 intgeneration =System.GC.GetGeneration(xlApp);
76 xlApp =null;
77 System.GC.Collect(generation);
78 }
79 }
80 }
81 returnsucceed;
82 }

二、使用Aspose.Cells.dll

Aspose.Cells 是 Aspose公司推出的导出Excel的控件,不依赖Office,商业软件,网上有破解 (下载见附件)。

代码如下:

1 public static bool ExportExcelWithAspose(System.Data.DataTable dt, string path)
2 {
3 boolsucceed =false;
4 if(dt !=null)
5 {
6 try
7 {
8 Aspose.Cells.License li =newAspose.Cells.License();
9 stringlic =Resources.License;
10 Stream s =newMemoryStream(ASCIIEncoding.Default.GetBytes(lic));
11 li.SetLicense(s);
12 
13 Aspose.Cells.Workbook workbook =newAspose.Cells.Workbook();
14 Aspose.Cells.Worksheet cellSheet =workbook.Worksheets[0];
15 
16 cellSheet.Name =dt.TableName;
17 
18 introwIndex =0;
19 intcolIndex =0;
20 intcolCount =dt.Columns.Count;
21 introwCount =dt.Rows.Count;
22 
23 //列名的处理
24 for(inti =0; i <colCount; i++)
25 {
26 cellSheet.Cells[rowIndex, colIndex].PutValue(dt.Columns[i].ColumnName);
27 cellSheet.Cells[rowIndex, colIndex].Style.Font.IsBold =true;
28 cellSheet.Cells[rowIndex, colIndex].Style.Font.Name ="宋体";
29 colIndex++;
30 }
31 
32 Aspose.Cells.Style style =workbook.Styles[workbook.Styles.Add()];
33 style.Font.Name ="Arial";
34 style.Font.Size =10;
35 Aspose.Cells.StyleFlag styleFlag =newAspose.Cells.StyleFlag();
36 cellSheet.Cells.ApplyStyle(style, styleFlag);
37 
38 rowIndex++;
39 
40 for(inti =0; i <rowCount; i++)
41 {
42 colIndex =0;
43 for(intj =0; j <colCount; j++)
44 {
45 cellSheet.Cells[rowIndex, colIndex].PutValue(dt.Rows[i][j].ToString());
46 colIndex++;
47 }
48 rowIndex++;
49 }
50 cellSheet.AutoFitColumns();
51 
52 path =Path.GetFullPath(path);
53 workbook.Save(path);
54 succeed =true;
55 }
56 catch(Exception ex)
57 {
58 succeed =false;
59 }
60 }
61 
62 returnsucceed;
63 }

三、 使用XML导出Excel

不依赖Office和其他第三方控件,需要事先准备一个模版。新建一个Excel文档,另存为XML 表格格式,将另存为的文件的扩展名改为xls,作为导出的模版。导出Excel时,用XMLDocment先打开模版,然后对模版进行增加修改操作,操作方法就是一般的XML操作方法。因为导出的文件扩展名是xls,与XML的文件格式不符,所以用Excel打开时会弹出提示。

代码如下:

1 public static bool ExportExcelWithXML(System.Data.DataTable dt, string path)
2 {
3 boolsucceed =false;
4 if(dt ==null)
5 {
6 //导出为XML格式的Excel文件,需要事先准备好XML格式的Excel文件作为模版
7 try
8 {
9 XmlDocument doc =newXmlDocument();
10 doc.Load(System.Windows.Forms.Application.StartupPath +@"\XLS\ExportXML.xls");
11 XmlNode root =doc.DocumentElement;
12 XmlNodeList xnlist =root.ChildNodes;
13 XmlElement sheet =null;
14 XmlElement documentPro =null;
15 XmlElement styles =null;
16 foreach(XmlNode xn inxnlist)
17 {
18 XmlElement xe =(XmlElement)xn;
19 if(xe.Name =="DocumentProperties")
20 {
21 documentPro =xe;
22 }
23 elseif(xe.Name =="Worksheet")
24 {
25 sheet =xe;
26 }
27 elseif(xe.Name =="Styles")
28 {
29 styles =xe;
30 }
31 }
32 
33 if(documentPro ==null||sheet ==null||styles ==null)
34 {
35 returnfalse;
36 }
37 
38 //写入Sheet名
39 sheet.SetAttribute("Name", ssNameSpace, dt.TableName);
40 
41 //添加Style
42 XmlElement styleColumnName =doc.CreateElement("Style", ssNameSpace);
43 styleColumnName.SetAttribute("ID", ssNameSpace, "s16");
44 XmlElement fontColumnName =doc.CreateElement("Font", ssNameSpace);
45 fontColumnName.SetAttribute("FontName", ssNameSpace, "Arial");
46 fontColumnName.SetAttribute("Family", xNameSpace, "Swiss");
47 fontColumnName.SetAttribute("Color", ssNameSpace, "#000000");
48 fontColumnName.SetAttribute("Bold", ssNameSpace, "1");
49 styleColumnName.AppendChild(fontColumnName);
50 styles.AppendChild(styleColumnName);
51 
52 XmlElement styleRow =doc.CreateElement("Style", ssNameSpace);
53 styleRow.SetAttribute("ID", ssNameSpace, "s17");
54 XmlElement fontRow =doc.CreateElement("Font", ssNameSpace);
55 fontRow.SetAttribute("FontName", ssNameSpace, "Arial");
56 fontRow.SetAttribute("Family", xNameSpace, "Swiss");
57 fontRow.SetAttribute("Color", ssNameSpace, "#000000");
58 styleRow.AppendChild(fontRow);
59 styles.AppendChild(styleRow);
60 
61 //写入表格内容
62 XmlNode table =sheet.FirstChild;
63 
64 //写入行列个数
65 ((XmlElement)table).SetAttribute("ExpandedColumnCount", ssNameSpace, dt.Columns.Count.ToString());
66 ((XmlElement)table).SetAttribute("ExpandedRowCount", ssNameSpace, (dt.Rows.Count +2).ToString());
67 
68 //添加列宽
69 for(inti =0; i <dt.Columns.Count; i++)
70 {
71 XmlElement column =doc.CreateElement("Column", ssNameSpace);
72 column.SetAttribute("Width", ssNameSpace, "100");
73 column.SetAttribute("AutoFitWidth", ssNameSpace, "1");
74 table.AppendChild(column);
75 }
76 
77 //添加列名
78 XmlElement columnName =doc.CreateElement("Row", ssNameSpace);
79 for(inti =0; i <dt.Columns.Count; i++)
80 {
81 XmlElement columnCell =doc.CreateElement("Cell", ssNameSpace);
82 columnCell.SetAttribute("StyleID", ssNameSpace, "s16");
83 
84 XmlElement data =doc.CreateElement("ss:Data", ssNameSpace);
85 data.SetAttribute("Type", ssNameSpace, "String");
86 data.InnerText =dt.Columns[i].ToString();
87 
88 columnCell.AppendChild(data);
89 columnName.AppendChild(columnCell);
90 }
91 table.AppendChild(columnName);
92 
93 //添加行
94 for(inti =0; i <dt.Rows.Count; i++)
95 {
96 XmlElement row =doc.CreateElement("Row", ssNameSpace);
97 for(intj =0; j <dt.Columns.Count; j++)
98 {
99 XmlElement cell =doc.CreateElement("Cell", ssNameSpace);
100 cell.SetAttribute("StyleID", ssNameSpace, "s17");
101 
102 XmlElement data =doc.CreateElement("Data", ssNameSpace);
103 data.SetAttribute("Type", ssNameSpace, "String");
104 data.InnerText =dt.Rows[i][j].ToString();
105 
106 cell.AppendChild(data);
107 row.AppendChild(cell);
108 }
109 table.AppendChild(row);
110 }
111 
112 DateTime now =DateTime.Now;
113 stringtimeString =string.Format("{0}T{1}Z", now.ToShortDateString(), now.ToLongTimeString());
114 XmlNodeList docProNodeList =documentPro.ChildNodes;
115 foreach(XmlNode xn indocProNodeList)
116 {
117 if(xn.Name =="Author"||xn.Name =="LastAuthor")
118 {
119 //写入作者和修改者
120 xn.InnerText =Environment.UserName;
121 }
122 elseif(xn.Name =="Created"||xn.Name =="LastSaved")
123 {
124 //写入创建时间和修改时间
125 xn.InnerText =timeString;
126 }
127 elseif(xn.Name =="Company")
128 {
129 //写入公司名
130 xn.InnerText =System.Windows.Forms.Application.CompanyName;
131 }
132 }
133 
134 doc.Save(path);
135 succeed =true;
136 }
137 catch(Exception e)
138 {
139 succeed =false;
140 }
141 }
142 
143 returnsucceed;
144 }

转载于:https://www.cnblogs.com/zpc870921/p/3286664.html

将datatable导出为excel的三种方式(转)相关推荐

  1. Winform中通过NPOI导出Excel的三种方式(HSSFWorkbook,XSSFWorkbook,SXSSFWorkbook)附代码下载

    场景 HSSFworkbook,XSSFworkbook,SXSSFworkbook区别 HSSFWorkbook: 是操作Excel2003以前(包括2003)的版本,扩展名是.xls:导出exce ...

  2. 详解Springboot下载Excel的三种方式

    https://www.jb51.net/article/216656.htm 汇总一下浏览器下载和代码本地下载实现的3种方式. (其实一般都是在代码生成excel,然后上传到oss,然后传链接给前台 ...

  3. Java操作Excel三种方式POI、Hutool、EasyExcel

    Java操作Excel三种方式POI.Hutool.EasyExcel 1. Java操作Excel概述 1.1 Excel需求概述 1.2 Excel操作三种方式对比 2. ApachePOIExc ...

  4. python读文件的三种方式_Python|读、写Excel文件(三种模块三种方式)

    python读写excel的方式有很多,不同的模块在读写的讲法上稍有区别: 用xlrd和xlwt进行excel读写: 用openpyxl进行excel读写: import xlrd from xlut ...

  5. 导出excel的两种方式

    引言 导出excel就是将后台的数据在数据库中查找出来,然后再将数据存放进excel表格中,这种操作多用于一些统计表中,将table中的数据导出来,存放进excel表格中.(最近在将手机中的短信往电脑 ...

  6. html表格导出excel有几种方式

    html表格导出excel有几种方式 一. 前后端结合 利用 JavaScript 将表格内容转换为 Excel 文件格式,然后通过 Ajax 请求将文件数据发送给后台,再由后台返回该文件数据流,前端 ...

  7. SQL:使用备份向导、SQL命令、导出数据三种方式对已建立的数据库进行备份

    SQL:使用备份向导.SQL命令.导出数据三种方式对已建立的数据库进行备份 目录 题目要求 解题步骤 题目要求 使用备份向导备份数据库 "DEMO_4_2_2_1"到考生文件夹&q ...

  8. DataGridView导出到Excel的三个方法

    DataGridView导出到Excel的三个方法 原文:[转]DataGridView导出到Excel的三个方法 原文出处:http://www.yongfa365.com/Item/DataGri ...

  9. Excel中数据透视表数据源更新的三种方式

    Excel中数据透视表数据源更新的三种方式 1.在原有的基础上重新选择数据源 2.变数据源为表格形式,在创建一个透视表,之后如果添加的数据,选中透视表右键刷新即可 3.利用更新过的数据源再重新创建一个 ...

最新文章

  1. hadoop job 数量_大数据Hadoop常见面/笔试题
  2. PCB铜箔厚度、线宽与允许通多电流大小的关系
  3. c++如何把字符串转为变量名_如何优雅地计算多变量
  4. 002 辅助框架的设计
  5. IE新0day漏洞(979352)(又称极光零日漏洞)***将扩散
  6. 【励志好文】老爸推荐的好文,受益良多!
  7. 网页代码抓取工具_MAC网页颜色代码提取工具
  8. 蒙文字体怎么安装_焘哥带你玩转字体(三)字体的安装及显示问题
  9. ElasticSearch、kibana、head、ik分词器在Windows下的安装
  10. Eclipse Maven构建Spring MVC项目
  11. window 获取cpu型号_教你如何修改电脑上的CPU型号信息!
  12. Android 状态栏适配
  13. Ubuntu软件包升级失败的终极修复方法
  14. 安装 Adblock plus 插件彻底屏蔽Chrome 浏览器上的广告 以及Adblock plus 的使用教程(亲测有效)
  15. C++小游戏(2):打飞机
  16. 计算机安装不了cad2007,win7系统电脑中安装cad2007不兼容无法打开的解决方法
  17. 大数定理和中心极限定理的通俗理解。
  18. GitHub 各种开源项目
  19. 用lxml的xpath演示爬虫提取笑话集网页其中的标题,url,浏览数,日期,笑话内容
  20. python3:小练习

热门文章

  1. [react] 函数式组件有没有生命周期?为什么?
  2. React开发(124):ant design学习指南之form中的this.props.form
  3. React开发(111):写注释的方法
  4. react学习(38)----react是什么
  5. PS教程第十五课:图层是最基本的要求
  6. 前端学习(2779):项目功能介绍
  7. 工作174:数组转换为对象项目案例
  8. 前端学习(1648):前端系列实战课程之任务功能清单思路
  9. 前端学习(1601):状态提升
  10. 前端学习(975):bootstrap轮播图