一,如何把數據庫的數據導入到Excel?
(1)可以使用多種方式,但是較好的一種是使用NPOI。
(2)NPOI的缺陷:只能在Office2003中使用,Office2007無法使用NPOI,同時對於WPS也不能使用。
(3)使用是要引入NPOI的dll外部文件,下面的代碼使用了簡單三層的思想。
二,把數據庫中的數據導入到Excel的具體步驟:
protected void Button2_Click(object sender, EventArgs e)
{
try
{
//使用NPOI創建Excel
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.CreateSheet();
HSSFRow row;//使用三層得到所有的數據,數據量小時,可以這麼做,當數據量很大時,要使用DataReader
UserInfoBLL userBll = new UserInfoBLL();
IEnumerable<UserInfo> list = userBll.GetAll();//寫入Excel的第一行,標題
row = sheet.CreateRow(0);
row.CreateCell(0, HSSFCell.CELL_TYPE_STRING).SetCellValue("姓名");
row.CreateCell(1, HSSFCell.CELL_TYPE_STRING).SetCellValue("年齡");
row.CreateCell(2, HSSFCell.CELL_TYPE_STRING).SetCellValue("郵箱");
row.CreateCell(3, HSSFCell.CELL_TYPE_STRING).SetCellValue("手機");
row.CreateCell(4, HSSFCell.CELL_TYPE_STRING).SetCellValue("時間");
row.CreateCell(5, HSSFCell.CELL_TYPE_STRING).SetCellValue("地址");
row.CreateCell(6, HSSFCell.CELL_TYPE_STRING).SetCellValue("備註");//依次遍歷結果集,並賦值
int i=1;
foreach(var userinfo in list)
{
row = sheet.CreateRow(i);
row.CreateCell(0, HSSFCell.CELL_TYPE_STRING).SetCellValue(userinfo.UserName);
row.CreateCell(1, HSSFCell.CELL_TYPE_NUMERIC).SetCellValue(Convert.ToInt32(userinfo.Age));
row.CreateCell(2, HSSFCell.CELL_TYPE_STRING).SetCellValue(userinfo.Email);
row.CreateCell(3, HSSFCell.CELL_TYPE_STRING).SetCellValue(userinfo.Telephone);
row.CreateCell(4, HSSFCell.CELL_TYPE_NUMERIC).SetCellValue(Convert.ToDateTime( userinfo.AddDate));
row.CreateCell(5, HSSFCell.CELL_TYPE_STRING).SetCellValue(userinfo.Address);
row.CreateCell(6, HSSFCell.CELL_TYPE_STRING).SetCellValue(userinfo.Remarks);
i++;
}//操作文件流,寫入到Excel中
using (Stream stream = new FileStream(@"G:\userInfoOut.xls", FileMode.OpenOrCreate, FileAccess.ReadWrite))
{
workbook.Write(stream);
}
Response.Write("導出成功");
}
catch (Exception ex)
{
Response.Write("錯誤:" + ex.Message);
}
}
三 ,參考
(1),此種做法只能針對數據量較小的數據,對於數據很多的導出,則不能使用這種方式。
(2),如何使用NPOI把Excel中的數據導入到數據庫,請參考本博客相關文章。