c# .Net :Excel NPOI導入導出操作教程之資料庫表信息數據導出到一個Excel文件並寫到磁碟示例分享 ...
string sql = @"select * from T_Excel";
————————————————DataTable Star————————————————
DataTable dt = SqlHelper.ExecuteDataTable(sql);
if (dt.Rows.Count > 0)
{
//創建工作簿
IWorkbook workbook = new HSSFWorkbook();
//創建表
ISheet sheet = workbook.CreateSheet("DBToExcel");
IRow row0 = sheet.CreateRow(0);
row0.CreateCell(0).SetCellValue("id信息");
row0.CreateCell(1).SetCellValue("名稱信息");
row0.CreateCell(2).SetCellValue("備註信息");
for (int r = 0; r < dt.Rows.Count; r++)
{
//創建行接受DataTable的行數據
IRow row = sheet.CreateRow(r + 1);
row.CreateCell(0).SetCellValue((int)dt.Rows[r]["Id"]);
row.CreateCell(1).SetCellValue(dt.Rows[r]["Name"].ToString());
row.CreateCell(2).SetCellValue(dt.Rows[r]["Remarks"].ToString());
}
————————————————DataTable END————————————————
————————————————SqlDataReader ————————————————
//SqlDataReader reader = SqlHelper.ExecuteReader(sql);
//if (reader.HasRows)
//{
// //創建工作簿
// IWorkbook workbook = new HSSFWorkbook();
// //創建工作表
// ISheet sheet = workbook.CreateSheet("DBToExcel");
// int rowIndex = 0;
// while (reader.Read())
// {
// //讀取一條數據就創建一行row
// IRow row = sheet.CreateRow(rowIndex);
// //記錄讀取數據行數
// rowIndex++;
// row.CreateCell(0).SetCellValue(reader.GetInt32(0));
// row.CreateCell(1).SetCellValue(reader.GetString(1));
// row.CreateCell(2).SetCellValue(reader.GetString(2));
// }
————————————————SqlDataReader ————————————————
using (FileStream saveurl = File.OpenWrite(@"C:\Users\Administrator\Desktop\112.xls"))
{
workbook.Write(saveurl);
Title = "已經導出數據!";
}
}
else
{
Title = "沒有導出任何數據!";
}
string sql = @"select * from T_Excel";
DataTable dt = SqlHelper.ExecuteDataTable(sql);
if (dt.Rows.Count > 0)
{
//創建工作簿
IWorkbook workbook = new HSSFWorkbook();
//創建表
ISheet sheet = workbook.CreateSheet("DBToExcel");
IRow row0 = sheet.CreateRow(0);
row0.CreateCell(0).SetCellValue("id信息");
row0.CreateCell(1).SetCellValue("名稱信息");
row0.CreateCell(2).SetCellValue("備註信息");
for (int r = 0; r < dt.Rows.Count; r++)
{
//創建行接受DataTable的行數據
IRow row = sheet.CreateRow(r + 1);
row.CreateCell(0).SetCellValue((int)dt.Rows[r]["Id"]);
row.CreateCell(1).SetCellValue(dt.Rows[r]["Name"].ToString());
row.CreateCell(2).SetCellValue(dt.Rows[r]["Remarks"].ToString());
}
//SqlDataReader reader = SqlHelper.ExecuteReader(sql);
//if (reader.HasRows)
//{
// //創建工作簿
// IWorkbook workbook = new HSSFWorkbook();
// //創建工作表
// ISheet sheet = workbook.CreateSheet("DBToExcel");
// int rowIndex = 0;
// while (reader.Read())
// {
// //讀取一條數據就創建一行row
// IRow row = sheet.CreateRow(rowIndex);
// //記錄讀取數據行數
// rowIndex++;
// row.CreateCell(0).SetCellValue(reader.GetInt32(0));
// row.CreateCell(1).SetCellValue(reader.GetString(1));
// row.CreateCell(2).SetCellValue(reader.GetString(2));
// }
using (FileStream saveurl = File.OpenWrite(@"C:\Users\Administrator\Desktop\112.xls"))
{
workbook.Write(saveurl);
Title = "已經導出數據!";
}
}
else
{
Title = "沒有導出任何數據!";
}