配色: 字号:
DataTable导出Excel的三种方式
2016-10-27 | 阅:  转:  |  分享 
  
DataTable导出Excel的三种方式

新加一种,使用



使用NPOI导入导出标准Excel



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



需要安装Office



代码如下:







复制代码

2publicstaticboolExportExcel(System.Data.DataTabledt,stringpath)

3{

4boolsucceed=false;

5if(dt!=null)

6{

7Microsoft.Office.Interop.Excel.ApplicationxlApp=null;

8try

9{

10xlApp=newMicrosoft.Office.Interop.Excel.ApplicationClass();

11}

12catch(Exceptionex)

13{

14throwex;

15}

16

17if(xlApp!=null)

18{

19try

20{

21Microsoft.Office.Interop.Excel.WorkbookxlBook=xlApp.Workbooks.Add(true);

22objectoMissing=System.Reflection.Missing.Value;

23Microsoft.Office.Interop.Excel.WorksheetxlSheet=null;

24

25xlSheet=(Worksheet)xlBook.Worksheets[1];

26xlSheet.Name=dt.TableName;

27

28introwIndex=1;

29intcolIndex=1;

30intcolCount=dt.Columns.Count;

31introwCount=dt.Rows.Count;

32

33//列名的处理

34for(inti=0;i
35{

36xlSheet.Cells[rowIndex,colIndex]=dt.Columns[i].ColumnName;

37colIndex++;

38}

39//列名加粗显示

40xlSheet.get_Range(xlSheet.Cells[rowIndex,1],xlSheet.Cells[rowIndex,colCount]).Font.Bold=true;

41xlSheet.get_Range(xlSheet.Cells[rowIndex,1],xlSheet.Cells[rowCount+1,colCount]).Font.Name="Arial";

42xlSheet.get_Range(xlSheet.Cells[rowIndex,1],xlSheet.Cells[rowCount+1,colCount]).Font.Size="10";

43rowIndex++;

44

45for(inti=0;i
46{

47colIndex=1;

48for(intj=0;j
49{

50xlSheet.Cells[rowIndex,colIndex]=dt.Rows[i][j].ToString();

51colIndex++;

52}

53rowIndex++;

54}

55xlSheet.Cells.EntireColumn.AutoFit();

56

57xlApp.DisplayAlerts=false;

58path=Path.GetFullPath(path);

59xlBook.SaveCopyAs(path);

60xlBook.Close(false,null,null);

61xlApp.Workbooks.Close();

62Marshal.ReleaseComObject(xlSheet);

63Marshal.ReleaseComObject(xlBook);

64xlBook=null;

65succeed=true;

66}

67catch(Exceptionex)

68{

69succeed=false;

70}

71finally

72{

73xlApp.Quit();

74Marshal.ReleaseComObject(xlApp);

75intgeneration=System.GC.GetGeneration(xlApp);

76xlApp=null;

77System.GC.Collect(generation);

78}

79}

80}

81returnsucceed;

82}

复制代码

二、使用Aspose.Cells.dll



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



代码如下:



复制代码

1publicstaticboolExportExcelWithAspose(System.Data.DataTabledt,stringpath)

2{

3boolsucceed=false;

4if(dt!=null)

5{

6try

7{

8Aspose.Cells.Licenseli=newAspose.Cells.License();

9stringlic=Resources.License;

10Streams=newMemoryStream(ASCIIEncoding.Default.GetBytes(lic));

11li.SetLicense(s);

12

13Aspose.Cells.Workbookworkbook=newAspose.Cells.Workbook();

14Aspose.Cells.WorksheetcellSheet=workbook.Worksheets[0];

15

16cellSheet.Name=dt.TableName;

17

18introwIndex=0;

19intcolIndex=0;

20intcolCount=dt.Columns.Count;

21introwCount=dt.Rows.Count;

22

23//列名的处理

24for(inti=0;i
25{

26cellSheet.Cells[rowIndex,colIndex].PutValue(dt.Columns[i].ColumnName);

27cellSheet.Cells[rowIndex,colIndex].Style.Font.IsBold=true;

28cellSheet.Cells[rowIndex,colIndex].Style.Font.Name="宋体";

29colIndex++;

30}

31

32Aspose.Cells.Stylestyle=workbook.Styles[workbook.Styles.Add()];

33style.Font.Name="Arial";

34style.Font.Size=10;

35Aspose.Cells.StyleFlagstyleFlag=newAspose.Cells.StyleFlag();

36cellSheet.Cells.ApplyStyle(style,styleFlag);

37

38rowIndex++;

39

40for(inti=0;i
41{

42colIndex=0;

43for(intj=0;j
44{

45cellSheet.Cells[rowIndex,colIndex].PutValue(dt.Rows[i][j].ToString());

46colIndex++;

47}

48rowIndex++;

49}

50cellSheet.AutoFitColumns();

51

52path=Path.GetFullPath(path);

53workbook.Save(path);

54succeed=true;

55}

56catch(Exceptionex)

57{

58succeed=false;

59}

60}

61

62returnsucceed;

63}

复制代码





三、使用XML导出Excel



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



代码如下:



复制代码

1publicstaticboolExportExcelWithXML(System.Data.DataTabledt,stringpath)

2{

3boolsucceed=false;

4if(dt==null)

5{

6//导出为XML格式的Excel文件,需要事先准备好XML格式的Excel文件作为模版

7try

8{

9XmlDocumentdoc=newXmlDocument();

10doc.Load(System.Windows.Forms.Application.StartupPath+@"\XLS\ExportXML.xls");

11XmlNoderoot=doc.DocumentElement;

12XmlNodeListxnlist=root.ChildNodes;

13XmlElementsheet=null;

14XmlElementdocumentPro=null;

15XmlElementstyles=null;

16foreach(XmlNodexninxnlist)

17{

18XmlElementxe=(XmlElement)xn;

19if(xe.Name=="DocumentProperties")

20{

21documentPro=xe;

22}

23elseif(xe.Name=="Worksheet")

24{

25sheet=xe;

26}

27elseif(xe.Name=="Styles")

28{

29styles=xe;

30}

31}

32

33if(documentPro==null||sheet==null||styles==null)

34{

35returnfalse;

36}

37

38//写入Sheet名

39sheet.SetAttribute("Name",ssNameSpace,dt.TableName);

40

41//添加Style

42XmlElementstyleColumnName=doc.CreateElement("Style",ssNameSpace);

43styleColumnName.SetAttribute("ID",ssNameSpace,"s16");

44XmlElementfontColumnName=doc.CreateElement("Font",ssNameSpace);

45fontColumnName.SetAttribute("FontName",ssNameSpace,"Arial");

46fontColumnName.SetAttribute("Family",xNameSpace,"Swiss");

47fontColumnName.SetAttribute("Color",ssNameSpace,"#000000");

48fontColumnName.SetAttribute("Bold",ssNameSpace,"1");

49styleColumnName.AppendChild(fontColumnName);

50styles.AppendChild(styleColumnName);

51

52XmlElementstyleRow=doc.CreateElement("Style",ssNameSpace);

53styleRow.SetAttribute("ID",ssNamewww.baiyuewang.netSpace,"s17");

54XmlElementfontRow=doc.CreateElement("Font",ssNameSpace);

55fontRow.SetAttribute("FontName",ssNameSpace,"Arial");

56fontRow.SetAttribute("Family",xNameSpace,"Swiss");

57fontRow.SetAttribute("Color",ssNameSpace,"#000000");

58styleRow.AppendChild(fontRow);

59styles.AppendChild(styleRow);

60

61//写入表格内容

62XmlNodetable=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//添加列宽

69for(inti=0;i
70{

71XmlElementcolumn=doc.CreateElement("Column",ssNameSpace);

72column.SetAttribute("Width",ssNameSpace,"100");

73column.SetAttribute("AutoFitWidth",ssNameSpace,"1");

74table.AppendChild(column);

75}

76

77//添加列名

78XmlElementcolumnName=doc.CreateElement("Row",ssNameSpace);

79for(inti=0;i
80{

81XmlElementcolumnCell=doc.CreateElement("Cell",ssNameSpace);

82columnCell.SetAttribute("StyleID",ssNameSpace,"s16");

83

84XmlElementdata=doc.CreateElement("ss:Data",ssNameSpace);

85data.SetAttribute("Type",ssNameSpace,"String");

86data.InnerText=dt.Columns[i].ToString();

87

88columnCell.AppendChild(data);

89columnName.AppendChild(columnCell);

90}

91table.AppendChild(columnName);

92

93//添加行

94for(inti=0;i
95{

96XmlElementrow=doc.CreateElement("Row",ssNameSpace);

97for(intj=0;j
98{

99XmlElementcell=doc.CreateElement("Cell",ssNameSpace);

100cell.SetAttribute("StyleID",ssNameSpace,"s17");

101

102XmlElementdata=doc.CreateElement("Data",ssNameSpace);

103data.SetAttribute("Type",ssNameSpace,"String");

104data.InnerText=dt.Rows[i][j].ToString();

105

106cell.AppendChild(data);

107row.AppendChild(cell);

108}

109table.AppendChild(row);

110}

111

112DateTimenow=DateTime.Now;

113stringtimeString=string.Format("{0}T{1}Z",now.ToShortDateString(),now.ToLongTimeString());

114XmlNodeListdocProNodeList=documentPro.ChildNodes;

115foreach(XmlNodexnindocProNodeList)

116{

117if(xn.Name=="Author"||xn.Name=="LastAuthor")

118{

119//写入作者和修改者

120xn.InnerText=Environment.UserName;

121}

122elseif(xn.Name=="Created"||xn.Name=="LastSaved")

123{

124//写入创建时间和修改时间

125xn.InnerText=timeString;

126}

127elseif(xn.Name=="Company")

128{

129//写入公司名

130xn.InnerText=System.Windows.Forms.Application.CompanyName;

131}

132}

133

134doc.Save(path);

135succeed=true;

136}

137catch(Exceptione)

138{

139succeed=false;

140}

141}

142

143returnsucceed;

144}

复制代码









总结:第二、三种方法导出速度很快;第二种方法使用上最简单,但需要购买或破解;第三种方法依赖最小,便于代码移植,但使用上略显繁琐(需要大量的XML操作)。

献花(0)
+1
(本文系thedust79首藏)