2011年3月14日 星期一

NOPI匯出excel

protected void export_excel(DataTable dt, String filename)
{
// 產生 Excel 資料流。
MemoryStream ms = DataTableRenderToExcel.RenderDataTableToExcel(dt) as MemoryStream;
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.CreateSheet("人員清單");
// 建立儲存格樣式
HSSFCellStyle style1 = workbook.CreateCellStyle();
style1.Alignment = HSSFCellStyle.ALIGN_CENTER;
//表頭置中
HSSFRow dataRow = sheet.CreateRow(0);
HSSFCell cell = sheet.CreateRow(0).CreateCell(0);
foreach (DataColumn column in dt.Columns)
{
dataRow.CreateCell(column.Ordinal).SetCellValue(column.ColumnName);
dataRow.GetCell(column.Ordinal).CellStyle = style1;
}
//設定表頭寬度
sheet.SetColumnWidth(0, dt.Columns[0].ToString().Length * 700);
sheet.SetColumnWidth(1, dt.Columns[1].ToString().Length * 1000);
sheet.SetColumnWidth(2, dt.Columns[2].ToString().Length * 1500);
sheet.SetColumnWidth(3, dt.Columns[3].ToString().Length * 3000);
//內容
for (int i = 0; i < dt.Rows.Count; i++)
{
dataRow = sheet.CreateRow(i + 1);
for (int j = 0; j < dt.Columns.Count; j++)
{
dataRow.CreateCell(j).SetCellValue(dt.Rows[i][j].ToString());
}}
workbook.Write(ms);
Response.AddHeader("Content-Disposition", string.Format("attachment; filename=" + System.Web.HttpUtility.UrlEncode(filename, System.Text.Encoding.UTF8) + ".xls"));
Response.BinaryWrite(ms.ToArray());
ms.Close();
ms.Dispose();
}

沒有留言:

張貼留言