C#中使用NPIO实现导入导出Excel简单操作
生活随笔
收集整理的這篇文章主要介紹了
C#中使用NPIO实现导入导出Excel简单操作
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
本文介紹了在Winform中使用NPOI(PIO項(xiàng)目下的.Net組件)來(lái)操作Excel文件,而無(wú)需安裝Office。
要實(shí)現(xiàn)的效果是這樣的:
1、導(dǎo)出Excel:根據(jù)指定datatable,彈出導(dǎo)出窗口,用戶自定義路徑、導(dǎo)出名,然后導(dǎo)出。
2、導(dǎo)入Excel:彈出導(dǎo)入窗口,用戶自定義導(dǎo)入Excel文件,導(dǎo)入到datatable中。
首先,需要在NuGet程序包中搜索并下載NPOI組件,如下圖所示:
再添加一個(gè)ExcelHelper操作類(lèi),網(wǎng)上很多例子,我簡(jiǎn)化了很多樣式相關(guān)的代碼,只留下主要功能,并且自測(cè)沒(méi)問(wèn)題,附上ExcelHelper操作類(lèi):
?
public class ExcelHelp{/// <summary>///將datatable流文件導(dǎo)出到指定路徑的Excel中/// </summary>/// <param name="sourceTable"></param>public virtual void DataTableExportExcel(DataTable sourceTable){MemoryStream ms = DataTableToExcel(sourceTable);string saveFileName = "";bool fileSaved = false;SaveFileDialog saveDialog = new SaveFileDialog();//打開(kāi)選擇保存窗口saveDialog.DefaultExt = "xls";saveDialog.Filter = "Excel文件|*.xls";//保存窗口的文件篩選saveDialog.FileName = "MyExcel";//默認(rèn)文件名稱saveDialog.ShowDialog();saveFileName = saveDialog.FileName;if (saveFileName.IndexOf(":") < 0) return; //用戶點(diǎn)了取消if (saveFileName != ""){try{FileStream fs = new FileStream(saveDialog.FileName, FileMode.Create);fs.Write(ms.GetBuffer(), 0, ms.GetBuffer().Length);ms.Close();ms.Dispose();fs.Close();fileSaved = true;}catch (Exception ex){fileSaved = false;MessageBox.Show("導(dǎo)出文件時(shí)出錯(cuò),文件可能正被打開(kāi)!\n" + ex.Message);}}else{fileSaved = false;}GC.Collect();//強(qiáng)行銷(xiāo)毀if (fileSaved && File.Exists(saveFileName)){MessageBox.Show("導(dǎo)出成功!", "通知");}else{MessageBox.Show("導(dǎo)出失敗!", "通知");}}/// <summary>/// 根據(jù)指定流文件將Excel導(dǎo)入到datatable中/// </summary>public virtual void ExcelExportDataTable(){OpenFileDialog fileDialog = new OpenFileDialog();fileDialog.Filter = "Excel文件|*.xls";fileDialog.InitialDirectory = "E:\\";//設(shè)置默認(rèn)打開(kāi)路徑if (fileDialog.ShowDialog() == DialogResult.OK){string fileName = fileDialog.FileName;//得到文件所在位置FileStream fs = new FileStream(fileDialog.FileName, FileMode.Open,FileAccess.Read);DataTable dt = ExcelToDataTable(fs,0,0);}}/// <summary>/// 將datatable中的數(shù)據(jù)放入內(nèi)存流中/// </summary>/// <param name="souruceTable">來(lái)源datatable</param>/// <returns></returns>private MemoryStream DataTableToExcel(DataTable souruceTable){int rowCount = souruceTable.Rows.Count;int colCount = souruceTable.Columns.Count;HSSFWorkbook workbook = new HSSFWorkbook();//新建一個(gè)工作簿ISheet sheet = workbook.CreateSheet("mysheet");//新建一個(gè)sheet頁(yè)IRow headerRow = sheet.CreateRow(0);MemoryStream ms = new MemoryStream();//構(gòu)建標(biāo)題行foreach (DataColumn col in souruceTable.Columns){headerRow.CreateCell(col.Ordinal,CellType.String).SetCellValue(col.Caption);}//構(gòu)建數(shù)據(jù)行for (int i = 0; i < rowCount; i++){IRow dataRow = sheet.CreateRow(i + 1);for (int j = 0; j < colCount; j++){DataRow row = souruceTable.Rows[i];DataColumn col = souruceTable.Columns[j];dataRow.CreateCell(j).SetCellValue(row[col].ToString()); }}workbook.Write(ms);ms.Flush();ms.Position = 0;sheet = null;headerRow = null;workbook = null;return ms;}/// <summary>/// 將excel數(shù)據(jù)流中的數(shù)據(jù)轉(zhuǎn)化為datatable/// </summary>/// <param name="ExcelFileStream">指定流文件</param>/// <param name="SheetIndex">導(dǎo)入sheet頁(yè)頁(yè)號(hào)</param>/// <param name="HeaderRowIndex">行標(biāo)題行號(hào)</param>/// <returns></returns>private DataTable ExcelToDataTable(Stream ExcelFileStream, int SheetIndex, int HeaderRowIndex){HSSFWorkbook workbook = new HSSFWorkbook(ExcelFileStream);ISheet sheet = workbook.GetSheetAt(SheetIndex);DataTable table = new DataTable();/*根據(jù)標(biāo)題行索引構(gòu)建datatable列名*/IRow headerRow = sheet.GetRow(HeaderRowIndex);int cellCount = headerRow.LastCellNum;for (int i = headerRow.FirstCellNum; i < cellCount; i++){DataColumn column = new DataColumn(headerRow.GetCell(i).StringCellValue);table.Columns.Add(column);}/*構(gòu)建datatable表體*/int rowCount = sheet.LastRowNum;for (int i = (sheet.FirstRowNum + 1); i <= sheet.LastRowNum; i++){IRow row = sheet.GetRow(i);DataRow dataRow = table.NewRow();for (int j = row.FirstCellNum; j < cellCount; j++){if (row.GetCell(j) != null){dataRow[j] = row.GetCell(j).ToString();}}table.Rows.Add(dataRow);}ExcelFileStream.Close();workbook = null;sheet = null;return table;}}使用方法如下所示,導(dǎo)出Excel:
DataTable dt = InintTable(); ExcelHelp eh = new ExcelHelp(); eh.DataTableExportExcel(dt);//測(cè)試數(shù)據(jù) public DataTable InintTable() {DataTable dt = new DataTable("TestTable");dt.Columns.Add("Code", typeof(string));dt.Columns.Add("Name", typeof(string));dt.Columns.Add("Age", typeof(int));dt.Columns.Add("Time", typeof(DateTime));for (int i = 0; i < 30; i++){DataRow dr = dt.NewRow();dr["Code"] = (i + 100).ToString();dr["Name"] = "人員" + i.ToString();dr["Age"] = 20;dr["Time"] = DateTime.Now.AddDays(i);dt.Rows.Add(dr);}return dt; }導(dǎo)入Excel:
ExcelHelp eh = new ExcelHelp(); eh.ExcelExportDataTable();?
?
總結(jié)
以上是生活随笔為你收集整理的C#中使用NPIO实现导入导出Excel简单操作的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: LeetCode——350. 两个数组的
- 下一篇: C#实现 Linq 序列的Distinc