您的位置:首页 > 其它

DataTable导出Excel的三种方式

2012-09-27 19:58 459 查看
新加一种,使用

使用NPOI导入导出标准Excel

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

  需要安装Office

  代码如下:

2 public static bool ExportExcel(System.Data.DataTable dt, string path)
3 {
4 bool succeed = false;
5 if (dt != null)
6 {
7 Microsoft.Office.Interop.Excel.Application xlApp = null;
8 try
9 {
xlApp = new Microsoft.Office.Interop.Excel.ApplicationClass();
}
catch (Exception ex)
{
throw ex;
}

if (xlApp != null)
{
try
{
Microsoft.Office.Interop.Excel.Workbook xlBook = xlApp.Workbooks.Add(true);
object oMissing = System.Reflection.Missing.Value;
Microsoft.Office.Interop.Excel.Worksheet xlSheet = null;

xlSheet = (Worksheet)xlBook.Worksheets[1];
xlSheet.Name = dt.TableName;

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

//列名的处理
for (int i = 0; i < colCount; i++)
{
xlSheet.Cells[rowIndex, colIndex] = dt.Columns[i].ColumnName;
colIndex++;
}
//列名加粗显示
xlSheet.get_Range(xlSheet.Cells[rowIndex, 1], xlSheet.Cells[rowIndex, colCount]).Font.Bold = true;
xlSheet.get_Range(xlSheet.Cells[rowIndex, 1], xlSheet.Cells[rowCount + 1, colCount]).Font.Name = "Arial";
xlSheet.get_Range(xlSheet.Cells[rowIndex, 1], xlSheet.Cells[rowCount + 1, colCount]).Font.Size = "10";
rowIndex++;

for (int i = 0; i < rowCount; i++)
{
colIndex = 1;
for (int j = 0; j < colCount; j++)
{
xlSheet.Cells[rowIndex, colIndex] = dt.Rows[i][j].ToString();
colIndex++;
}
rowIndex++;
}
xlSheet.Cells.EntireColumn.AutoFit();

xlApp.DisplayAlerts = false;
path = Path.GetFullPath(path);
xlBook.SaveCopyAs(path);
xlBook.Close(false, null, null);
xlApp.Workbooks.Close();
Marshal.ReleaseComObject(xlSheet);
Marshal.ReleaseComObject(xlBook);
xlBook = null;
succeed = true;
}
catch (Exception ex)
{
succeed = false;
}
finally
{
xlApp.Quit();
Marshal.ReleaseComObject(xlApp);
int generation = System.GC.GetGeneration(xlApp);
xlApp = null;
System.GC.Collect(generation);
}
}
}
return succeed;
}

二、使用Aspose.Cells.dll

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

代码如下:

1 public static bool ExportExcelWithAspose(System.Data.DataTable dt, string path)
2 {
3 bool succeed = false;
4 if (dt != null)
5 {
6 try
7 {
8 Aspose.Cells.License li = new Aspose.Cells.License();
9 string lic = Resources.License;
Stream s = new MemoryStream(ASCIIEncoding.Default.GetBytes(lic));
li.SetLicense(s);

Aspose.Cells.Workbook workbook = new Aspose.Cells.Workbook();
Aspose.Cells.Worksheet cellSheet = workbook.Worksheets[0];

cellSheet.Name = dt.TableName;

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

//列名的处理
for (int i = 0; i < colCount; i++)
{
cellSheet.Cells[rowIndex, colIndex].PutValue(dt.Columns[i].ColumnName);
cellSheet.Cells[rowIndex, colIndex].Style.Font.IsBold = true;
cellSheet.Cells[rowIndex, colIndex].Style.Font.Name = "宋体";
colIndex++;
}

Aspose.Cells.Style style = workbook.Styles[workbook.Styles.Add()];
style.Font.Name = "Arial";
style.Font.Size = 10;
Aspose.Cells.StyleFlag styleFlag = new Aspose.Cells.StyleFlag();
cellSheet.Cells.ApplyStyle(style, styleFlag);

rowIndex++;

for (int i = 0; i < rowCount; i++)
{
colIndex = 0;
for (int j = 0; j < colCount; j++)
{
cellSheet.Cells[rowIndex, colIndex].PutValue(dt.Rows[i][j].ToString());
colIndex++;
}
rowIndex++;
}
cellSheet.AutoFitColumns();

path = Path.GetFullPath(path);
workbook.Save(path);
succeed = true;
}
catch (Exception ex)
{
succeed = false;
}
}

return succeed;
}

三、 使用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 bool succeed = false;
4 if (dt == null)
5 {
6 // 导出为XML格式的Excel文件,需要事先准备好XML格式的Excel文件作为模版
7 try
8 {
9 XmlDocument doc = new XmlDocument();
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 in xnlist)
17 {
18 XmlElement xe = (XmlElement)xn;
19 if (xe.Name == "DocumentProperties")
20 {
21 documentPro = xe;
22 }
23 else if (xe.Name == "Worksheet")
24 {
25 sheet = xe;
26 }
27 else if (xe.Name == "Styles")
28 {
29 styles = xe;
30 }
31 }
32
33 if (documentPro == null || sheet == null || styles == null)
34 {
35 return false;
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 (int i = 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 (int i = 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 (int i = 0; i < dt.Rows.Count; i++)
95 {
96 XmlElement row = doc.CreateElement("Row", ssNameSpace);
97 for (int j = 0; j < dt.Columns.Count; j++)
98 {
99 XmlElement cell = doc.CreateElement("Cell", ssNameSpace);
cell.SetAttribute("StyleID", ssNameSpace, "s17");

XmlElement data = doc.CreateElement("Data", ssNameSpace);
data.SetAttribute("Type", ssNameSpace, "String");
data.InnerText = dt.Rows[i][j].ToString();

cell.AppendChild(data);
row.AppendChild(cell);
}
table.AppendChild(row);
}

DateTime now = DateTime.Now;
string timeString = string.Format("{0}T{1}Z", now.ToShortDateString(), now.ToLongTimeString());
XmlNodeList docProNodeList = documentPro.ChildNodes;
foreach (XmlNode xn in docProNodeList)
{
if (xn.Name == "Author" || xn.Name == "LastAuthor")
{
// 写入作者和修改者
xn.InnerText = Environment.UserName;
}
else if (xn.Name == "Created" || xn.Name == "LastSaved")
{
// 写入创建时间和修改时间
xn.InnerText = timeString;
}
else if (xn.Name == "Company")
{
// 写入公司名
xn.InnerText = System.Windows.Forms.Application.CompanyName;
}
}

doc.Save(path);
succeed = true;
}
catch (Exception e)
{
succeed = false;
}
}

return succeed;
}

总结:第二、三种方法导出速度很快;第二种方法使用上最简单,但需要购买或破解;第三种方法依赖最小,便于代码移植,但使用上略显繁琐(需要大量的XML操作)。所以如果有条件购买或不介意破解的话,极力推荐第二种方法。

ExportExcelWithXML的模版: /Files/zhyt1985/ExportXML.rar

Aspose.Cells 4.8 & Help & License: /Files/zhyt1985/Aspose.Cells.rar
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: