今天搞了搞用asp.net導出Excel
這里用到了Npoi,需要的key在官網上下載下來用用.
protected void export_ServerClick(object sender, EventArgs e)
{
//添加dataGridView的數據
string sql = "select * from carinfo";
utils.DbHelper help = new utils.DbHelper();
DataTable tabele = help.ExecuteDataTable(sql);
this.GridView1.DataSource = tabele;
this.GridView1.DataBind();
//進行Excel生成創建Workbook創建操作
//創建workBook 不指定指定參數 表示創建一個新的工作本 也可以指定流
HSSFWorkbook workbook = new HSSFWorkbook();
//2.創建sheet 行
HSSFSheet sheet = workbook.CreateSheet("管理員");
//3.創建行
HSSFRow row = sheet.CreateRow(0);
//穿件列
HSSFCell cell1 = row.CreateCell(0);
cell1.SetCellValue("第一行第一列的值");
//設置行合並單元格
sheet.AddMergedRegion(new Region(0, 0, 0, 3));//從零行零列開始到零號零列結束
//設置行居中
HSSFCellStyle cellContenStyle = workbook.CreateCellStyle();//設置當前工作本的cell樣式
cellContenStyle.Alignment=2;//2為居中
//將行樣式賦給需要改變的樣式
cell1.CellStyle = cellContenStyle;
//創建標題行
HSSFRow rowTitle = sheet.CreateRow(1);
HSSFCell cellTitle0 = rowTitle.CreateCell(0);
cellTitle0.SetCellValue("id");
HSSFCell cellTitle1 = rowTitle.CreateCell(1);
cellTitle1.SetCellValue("car_type");
HSSFCell cellTitle2 = rowTitle.CreateCell(2);
cellTitle2.SetCellValue("car_band");
HSSFCell cellTitle3 = rowTitle.CreateCell(3);
cellTitle3.SetCellValue("car_price");
HSSFCell cellTitle4 = rowTitle.CreateCell(4);
cellTitle4.SetCellValue("car_awards");
//遍歷集合創建正文內容
int index = 1;
foreach (DataRow dataRow in tabele.Rows)
{
HSSFRow rowData = sheet.CreateRow(index++);
//創建單元格
HSSFCell cellData0 = rowData.CreateCell(0);
cellData0.SetCellValue(dataRow[0].ToString());
HSSFCell cellData1 = rowData.CreateCell(1);
cellData1.SetCellValue(dataRow["car_type"].ToString());
HSSFCell cellData2 = rowData.CreateCell(2);
cellData2.SetCellValue(dataRow["car_band"].ToString());
HSSFCell cellData3 = rowData.CreateCell(3);
cellData3.SetCellValue(dataRow["car_price"].ToString());
HSSFCell cellData4 = rowData.CreateCell(4);
cellData4.SetCellValue(dataRow["car_awards"].ToString());
}
using (FileStream stream = new FileStream(@"C:\Users\zxl\Desktop\zxl.xls",FileMode.Create)) {
workbook.Write(stream);
}
}
導出之后
感覺還不錯.
這里數據是用DataTable存的