一款實用的Datatable資料匯出為Excell的小程式。
aspx Cs:
protected void LinkButton1_Click(object sender, EventArgs e)
{
ClassAspose c = new ClassAspose();
DataTable dt = new DataTable();
dt.Columns.Add("Sex", typeof(string));
dt.Columns.Add("2", typeof(string));
dt.Columns.Add("3", typeof(string));
dt.Columns.Add("4", typeof(string));
dt.Columns.Add("5", typeof(string));
DataRow dr = dt.NewRow();
dr["Sex"] = "男";
dr["2"] = "a";
dr["3"] = "b";
dr["4"] = "c";
dr["5"] = "d";
dt.Rows.Add(dr);
DataRow dr1 = dt.NewRow();
dr1["Sex"] = "女";
dr1["2"] = "a";
dr1["3"] = "b";
dr1["4"] = "c";
dr1["5"] = "d";
dt.Rows.Add(dr1);
c.OutFileToDisk(dt, "呀迷路", @"e:\yamiluy.xls");
}
Cs:
/// <summary>
/// 匯出資料到本地
/// </summary>
/// <param name="dt">要匯出的資料</param>
/// <param name="tableName">表格標題</param>
/// <param name="path">儲存路徑</param>
public void OutFileToDisk(DataTable dt, string tableName, string path)
{
Workbook workbook = new Workbook(); //工作簿
Worksheet sheet = workbook.Worksheets[0]; //工作表
Cells cells = sheet.Cells;//單元格
//為標題設定樣式
Aspose.Cells.Style styleTitle = (Aspose.Cells.Style)workbook.Styles[workbook.Styles.Add()];//新增樣式
styleTitle.HorizontalAlignment = TextAlignmentType.Center;//文字居中
styleTitle.Font.Name = "宋體";//文字字型
styleTitle.Font.Size = 18;//文字大小
styleTitle.Font.IsBold = true;//粗體
//樣式2
Aspose.Cells.Style style2 = (Aspose.Cells.Style)workbook.Styles[workbook.Styles.Add()];//新增樣式
style2.HorizontalAlignment = TextAlignmentType.Center;//文字居中
style2.Font.Name = "宋體";//文字字型
style2.Font.Size = 14;//文字大小
style2.Font.IsBold = true;//粗體
style2.IsTextWrapped = true;//單元格內容自動換行
style2.Borders[BorderType.LeftBorder].LineStyle = CellBorderType.Thin;
style2.Borders[BorderType.RightBorder].LineStyle = CellBorderType.Thin;
style2.Borders[BorderType.TopBorder].LineStyle = CellBorderType.Thin;
style2.Borders[BorderType.BottomBorder].LineStyle = CellBorderType.Thin;
//樣式3
Aspose.Cells.Style style3 = (Aspose.Cells.Style)workbook.Styles[workbook.Styles.Add()];//新增樣式
style3.HorizontalAlignment = TextAlignmentType.Center;//文字居中
style3.Font.Name = "宋體";//文字字型
style3.Font.Size = 12;//文字大小
style3.Borders[BorderType.LeftBorder].LineStyle = CellBorderType.Thin;
style3.Borders[BorderType.RightBorder].LineStyle = CellBorderType.Thin;
style3.Borders[BorderType.TopBorder].LineStyle = CellBorderType.Thin;
style3.Borders[BorderType.BottomBorder].LineStyle = CellBorderType.Thin;
int Colnum = dt.Columns.Count;//表格列數
int Rownum = dt.Rows.Count;//表格行數
//生成行1 標題行
cells.Merge(0, 0, 1, Colnum);//合併單元格
cells[0, 0].PutValue(tableName);//填寫內容
cells[0, 0].SetStyle(styleTitle);
cells.SetRowHeight(0, 38);
//生成行2 列名行
for (int i = 0; i < Colnum; i++)
{
cells[1, i].PutValue(dt.Columns[i].ColumnName);
cells[1, i].SetStyle(style2);
cells.SetRowHeight(1, 25);
}
//生成資料行
for (int i = 0; i < Rownum; i++)
{
for (int k = 0; k < Colnum; k++)
{
cells[2 + i, k].PutValue(dt.Rows[i][k].ToString());
cells[2 + i, k].SetStyle(style3);
}
cells.SetRowHeight(2 + i, 24);
}
workbook.Save(path);
}
還要下載一個dll檔案:下載連結: 點選開啟連結(一切為了積分)