現在的項目需要導出和導入excel,為了簡單的導入導出去用一套收費的office組件對於項目不能接受,幸好找到了NPOI這個簡單開源的excel讀寫組件。
NPOI官網:http://npoi.codeplex.com/
1.簡單讀取excel數據到datatable
FileStream file = new FileStream(Server.MapPath(@"TemFiles\tem.xls"), FileMode.Open, FileAccess.Read);
//根據路徑通過已存在的excel來創建HSSFWorkbook,即整個excel文檔 HSSFWorkbook workbook = new HSSFWorkbook(file); //獲取excel的第一個sheet HSSFSheet sheet = workbook.GetSheetAt(0); DataTable table = new DataTable(); //獲取sheet的首行 HSSFRow headerRow = sheet.GetRow(0); //一行最后一個方格的編號 即總的列數 int cellCount = headerRow.LastCellNum; for (int i = headerRow.FirstCellNum; i < cellCount; i++) { DataColumn column = new DataColumn(headerRow.GetCell(i).StringCellValue); table.Columns.Add(column); } //最后一列的標號 即總的行數 int rowCount = sheet.LastRowNum; for (int i = (sheet.FirstRowNum + 1); i < sheet.LastRowNum; i++) { HSSFRow row = sheet.GetRow(i);
if (row== null)//這一句很關鍵,因為沒有數據的行默認是null
{
continue;
}
DataRow dataRow = table.NewRow(); for (int j = row.FirstCellNum; j < cellCount; j++) { if (row.GetCell(j) != null)//同理,沒有數據的單元格都默認是null dataRow[j] = row.GetCell(j).ToString(); } table.Rows.Add(dataRow); } workbook = null; sheet = null;
2.寫入數據到excel
FileStream file = new FileStream(Server.MapPath(@"TemFiles\tem.xls"), FileMode.Open, FileAccess.Read);
//根據路徑通過已存在的excel來創建HSSFWorkbook,即整個excel文檔 HSSFWorkbook workbook = new HSSFWorkbook(file);
HSSFSheet sheet1 =workbook .CreateSheet("Sheet1"); HSSFRow row1=sheet1.CreateRow(0); //行建好了,就可以建單元格了,比如創建A1位置的單元格: row1.CreateCell(0).SetCellValue(1); //SetCellValue有好幾種重載 //你可以設置單元格為bool、double、DateTime、string和HSSFRichTextString類型。 //其中對於string類型的重載調用的就是HSSFRichTextString類型的重載,所以是一樣的, //HSSFRichTextString可用於有字體或者Unicode的文本。 sheet1.CreateRow(0).CreateCell(0).SetCellValue("This is a Sample"); sheet1.GetRow(0).CreateCell(0).SetCellValue("This is a Sample");
npoi在下載時會附帶很多的sample,習慣上也和office組件沒有太大的區別,用起來還是很方便的