在實(shí)際項(xiàng)目中有很多場(chǎng)景遇到需要操作EXCEL文件,而常用到的庫(kù)就有NPOI;NPOI是開(kāi)源的POI 項(xiàng)目的.NET版,POI是一個(gè)開(kāi)源的Java讀寫(xiě)Excel、WORD等微軟OLE2組件文檔的項(xiàng)目, 使用 NPOI 你就可以在沒(méi)有安裝 Office 或者相應(yīng)環(huán)境的機(jī)器上對(duì) WORD/EXCEL 文檔進(jìn)行讀寫(xiě)。在處理Excel文件上,NPOI 可以同時(shí)兼容 xls 和 xlsx。 程序集構(gòu)成 一、引用 在NuGet里搜索NPOI,選擇下圖的項(xiàng)目安裝即可; 二、程序示例: 部分代碼如下: (1)導(dǎo)出EXCEL代碼 public void Export_Excel(string path) { string extension= Path.GetExtension(path).ToLower(); IWorkbook workbook; if (extension=='.xlsx') { workbook = new XSSFWorkbook(); } else { workbook = new HSSFWorkbook(); } ISheet sheet = workbook.CreateSheet('表1'); using(FileStream fs=new FileStream(path,FileMode.Create,FileAccess.ReadWrite)) { IRow row_Head = sheet.CreateRow(0); for (int i = 0; i < dataGridView1.Columns.Count; i++) { ICell cell = row_Head.CreateCell(i); cell.SetCellValue(dataGridView1.Columns[i].HeaderText); } for (int i = 0; i < dataGridView1.Rows.Count; i++) { IRow row1 = sheet.CreateRow(i + 1); for (int j = 0; j < dataGridView1.Columns.Count; j++) { ICell cell = row1.CreateCell(j); if(dataGridView1.Rows[i].Cells[j].Value==null) cell.SetCellValue(''); else cell.SetCellValue(dataGridView1.Rows[i].Cells[j].Value.ToString()); } } workbook.Write(fs); workbook.Close(); } } (2)讀取EXCEL文件代碼public void Import_Excel(string path) { DataTable dt = new DataTable(); using (FileStream fsRead = new FileStream(path, FileMode.Open, FileAccess.Read)) { string extension = Path.GetExtension(path).ToLower(); IWorkbook workbook; if (extension == '.xlsx') { workbook = new XSSFWorkbook(fsRead); } else { workbook = new HSSFWorkbook(fsRead); } ISheet sheet = workbook.GetSheetAt(0); IRow currentRow = sheet.GetRow(0); //最后一個(gè)方格的編號(hào) 即總的列數(shù) int cellCount = currentRow.LastCellNum; dataGridView1.DataSource = null; for (int i = 0; i < cellCount; i++) { //DataColumn dc = new DataColumn(); dt.Columns.Add( currentRow.GetCell(i).ToString());//增加列 } for (int j = 0; j <= sheet.LastRowNum - 1; j++) { dt.Rows.Add();//增加行 IRow currentRow1 = sheet.GetRow(j + 1); if (currentRow1 != null) { for (int c = 0; c < currentRow1.LastCellNum; c++) { ICell cell = currentRow1.GetCell(c); if (cell == null || cell.CellType == CellType.Blank) { dt.Rows[j][c] = DBNull.Value; } else { //如果當(dāng)前單元格不為空,則根據(jù)單元格的類(lèi)型獲取數(shù)據(jù) switch (cell.CellType) { //只有當(dāng)單元格的數(shù)據(jù)類(lèi)型是數(shù)字類(lèi)型的時(shí)候使用cell.NumericCellValue來(lái)獲取值。其余類(lèi)型都使用字符串來(lái)獲取.日期類(lèi)型數(shù)據(jù)插入單元格后也是CellType.NUMERIC case CellType.Numeric: //cell.NumericCellValue; dt.Rows[j][c] = cell.NumericCellValue; break; default: //cell.ToString(); dt.Rows[j][c] = cell.ToString(); break; } } } } } dataGridView1.DataSource = dt; workbook.Close(); } } 三、感謝您的閱讀,完整代碼已上傳,關(guān)注點(diǎn)贊后發(fā)送私信“NPOI”即可獲取。 |
|
來(lái)自: 小勛3z4x5gfoiq > 《c語(yǔ)言》