aspose将datatable导出2

     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;
10                     Stream s = new MemoryStream(ASCIIEncoding.Default.GetBytes(lic));
11                     li.SetLicense(s);
12 
13                     Aspose.Cells.Workbook workbook = new Aspose.Cells.Workbook();
14                     Aspose.Cells.Worksheet cellSheet = workbook.Worksheets[0];
15 
16                     cellSheet.Name = dt.TableName;
17 
18                     int rowIndex = 0;
19                     int colIndex = 0;
20                     int colCount = dt.Columns.Count;
21                     int rowCount = dt.Rows.Count;
22 
23                     //列名的处理
24                     for (int i = 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 = new Aspose.Cells.StyleFlag();
36                     cellSheet.Cells.ApplyStyle(style, styleFlag);
37 
38                     rowIndex++;
39 
40                     for (int i = 0; i < rowCount; i++)
41                     {
42                         colIndex = 0;
43                         for (int j = 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             return succeed;
63         }

posted on 2012-04-19 11:56  JQuery-Ch  阅读(406)  评论(0编辑  收藏  举报

导航