首先安裝NPOI ,點擊VS的—>工具—>NuGet包管理器—>管理解決方案的NuGet程序包
導出Excel如下:
/// <summary> /// 導出Excel /// </summary> /// <param name="TableName"></param> public static void ExportDataToExcel(DataTable TableName) { string FileName= DateTime.Now.GetHashCode().ToString(); SaveFileDialog saveFileDialog = new SaveFileDialog(); //設置文件標題 saveFileDialog.Title = "導出Excel文件"; //設置文件類型 saveFileDialog.Filter = "Excel 工作簿(*.xlsx)|*.xlsx|Excel 97-2003 工作簿(*.xls)|*.xls"; //設置默認文件類型顯示順序 saveFileDialog.FilterIndex = 1; //是否自動在文件名中添加擴展名 saveFileDialog.AddExtension = true; //是否記憶上次打開的目錄 saveFileDialog.RestoreDirectory = true; //設置默認文件名 saveFileDialog.FileName = FileName; //按下確定選擇的按鈕 if (saveFileDialog.ShowDialog() == DialogResult.OK) { //獲得文件路徑 string localFilePath = saveFileDialog.FileName.ToString(); //數據初始化 int TotalCount; //總行數 int RowRead = 0; //已讀行數 int Percent = 0; //百分比 TotalCount = TableName.Rows.Count; //NPOI IWorkbook workbook; string FileExt = Path.GetExtension(localFilePath).ToLower(); if (FileExt == ".xlsx") { workbook = new XSSFWorkbook(); } else if (FileExt == ".xls") { workbook = new HSSFWorkbook(); } else { workbook = null; } if (workbook == null) { return; } ISheet sheet = string.IsNullOrEmpty(FileName) ? workbook.CreateSheet("Sheet1") : workbook.CreateSheet(FileName); //秒鍾 Stopwatch timer = new Stopwatch(); timer.Start(); try { //讀取標題 IRow rowHeader = sheet.CreateRow(0); for (int i = 0; i < TableName.Columns.Count; i++) { ICell cell = rowHeader.CreateCell(i); cell.SetCellValue(TableName.Columns[i].ColumnName); } //讀取數據 for (int i = 0; i < TableName.Rows.Count; i++) { IRow rowData = sheet.CreateRow(i + 1); for (int j = 0; j < TableName.Columns.Count; j++) { ICell cell = rowData.CreateCell(j); cell.SetCellValue(TableName.Rows[i][j].ToString()); } //狀態欄顯示 RowRead++; Percent = (int)(100 * RowRead / TotalCount); Application.DoEvents(); } Application.DoEvents(); //轉為字節數組 MemoryStream stream = new MemoryStream(); workbook.Write(stream); var buf = stream.ToArray(); //保存為Excel文件 using (FileStream fs = new FileStream(localFilePath, FileMode.Create, FileAccess.Write)) { fs.Write(buf, 0, buf.Length); fs.Flush(); fs.Close(); } Application.DoEvents(); //關閉秒鍾 timer.Reset(); timer.Stop(); //成功提示 if (MessageBox.Show("導出成功,是否立即打開?", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.Yes) { System.Diagnostics.Process.Start(localFilePath); } } catch (Exception ex) { MessageBox.Show(ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Information); } finally { //關閉秒鍾 timer.Reset(); timer.Stop(); } } }
/// <summary> /// 導出Excel模板 /// </summary> public static void ExportExampleToExcel() { DataTable TableName = new DataTable(); TableName.Columns.Add("字段1", typeof(string)); TableName.Columns.Add("字段2", typeof(string)); TableName.Columns.Add("字段3", typeof(string)); TableName.Columns.Add("字段4", typeof(string)); TableName.Columns.Add("字段5", typeof(string)); TableName.Columns.Add("字段6", typeof(string)); TableName.Columns.Add("字段7", typeof(string)); TableName.Columns.Add("字段8", typeof(string)); TableName.Columns.Add("字段9", typeof(string)); TableName.Columns.Add("字段10", typeof(string)); TableName.Columns.Add("字段12", typeof(string)); TableName.Columns.Add("字段13", typeof(string)); TableName.Columns.Add("字段14", typeof(string)); TableName.Columns.Add("字段15", typeof(string));
string FileName = "模板信息導入Excel模板"; SaveFileDialog saveFileDialog = new SaveFileDialog(); //設置文件標題 saveFileDialog.Title = "導出Excel文件"; //設置文件類型 saveFileDialog.Filter = "Excel 工作簿(*.xlsx)|*.xlsx|Excel 97-2003 工作簿(*.xls)|*.xls"; //設置默認文件類型顯示順序 saveFileDialog.FilterIndex = 1; //是否自動在文件名中添加擴展名 saveFileDialog.AddExtension = true; //是否記憶上次打開的目錄 saveFileDialog.RestoreDirectory = true; //設置默認文件名 saveFileDialog.FileName = FileName; //按下確定選擇的按鈕 if (saveFileDialog.ShowDialog() == DialogResult.OK) { //獲得文件路徑 string localFilePath = saveFileDialog.FileName.ToString(); //數據初始化 int TotalCount; //總行數 int RowRead = 0; //已讀行數 int Percent = 0; //百分比 TotalCount = 15; //NPOI IWorkbook workbook; string FileExt = Path.GetExtension(localFilePath).ToLower(); if (FileExt == ".xlsx") { workbook = new XSSFWorkbook(); } else if (FileExt == ".xls") { workbook = new HSSFWorkbook(); } else { workbook = null; } if (workbook == null) { return; } ISheet sheet = string.IsNullOrEmpty(FileName) ? workbook.CreateSheet("Sheet1") : workbook.CreateSheet(FileName); //秒鍾 Stopwatch timer = new Stopwatch(); timer.Start(); try { //讀取標題 IRow rowHeader = sheet.CreateRow(0); for (int i = 0; i < TableName.Columns.Count; i++) { ICell cell = rowHeader.CreateCell(i); cell.SetCellValue(TableName.Columns[i].ColumnName); } Application.DoEvents(); //轉為字節數組 MemoryStream stream = new MemoryStream(); workbook.Write(stream); var buf = stream.ToArray(); //保存為Excel文件 using (FileStream fs = new FileStream(localFilePath, FileMode.Create, FileAccess.Write)) { fs.Write(buf, 0, buf.Length); fs.Flush(); fs.Close(); } Application.DoEvents(); //關閉秒鍾 timer.Reset(); timer.Stop(); //成功提示 if (MessageBox.Show("導出成功,是否立即打開?", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.Yes) { System.Diagnostics.Process.Start(localFilePath); } } catch (Exception ex) { MessageBox.Show(ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Information); } finally { //關閉秒鍾 timer.Reset(); timer.Stop(); } } }
導入方法如下:
/// <summary> /// 將excel導入到datatable /// </summary> /// <param name="nosqllist">存放數據庫取出的編號list</param> /// <param name="msge">返回結果</param> /// <returns>返回datatable</returns> public static DataTable ExcelToDataTable(List<string> nosqllist,out string msge) { bool isColumnName = true;//第一行是否是列名 msge = "0"; string filePath = "";//excel路徑 List<string> NoList = new List<string>();//儲存編號,防止重復 //打開文件對話框選擇文件 OpenFileDialog file = new OpenFileDialog(); file.Filter = "Excel(*.xlsx)|*.xlsx|Excel(*.xls)|*.xls"; file.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop); file.Multiselect = false; if (file.ShowDialog() == DialogResult.OK) { filePath = file.FileName; } DataTable dataTable = null; FileStream fs = null; DataColumn column = null; DataRow dataRow = null; IWorkbook workbook = null; ISheet sheet = null; IRow row = null; ICell cell = null; IRow rowisrepeat = null; ICell cellisrepeat = null; int startRow = 0; try { using (fs = File.OpenRead(filePath)) { // 2007版本 if (filePath.IndexOf(".xlsx") > 0) workbook = new XSSFWorkbook(fs); // 2003版本 else if (filePath.IndexOf(".xls") > 0) workbook = new HSSFWorkbook(fs); if (workbook != null) { sheet = workbook.GetSheetAt(0);//讀取第一個sheet,當然也可以循環讀取每個sheet dataTable = new DataTable(); if (sheet != null) { int rowCount = sheet.LastRowNum;//總行數 if (rowCount > 0) { IRow firstRow = sheet.GetRow(0);//第一行 #region 判斷列名是否一致 string[] exlist = GetStringNum();//得到定義的標題 for(int i=0;i< exlist.Length;i++) { if(Convert.ToString(firstRow.Cells[i])!= exlist[i]) { msge = "第"+i+1+"列標題不是"+exlist[i]+",列標題錯誤!"; return dataTable; } } #endregion int cellCount = firstRow.LastCellNum;//列數 //構建datatable的列 if (isColumnName) { startRow = 1;//如果第一行是列名,則從第二行開始讀取 for (int i = firstRow.FirstCellNum; i < cellCount; ++i) { cell = firstRow.GetCell(i); if (cell != null) { if (cell.StringCellValue != null) { column = new DataColumn(cell.StringCellValue); dataTable.Columns.Add(column); } } } } else { for (int i = firstRow.FirstCellNum; i < cellCount; ++i) { column = new DataColumn("column" + (i + 1)); dataTable.Columns.Add(column); } } #region 判斷編號是否有重復 NoList = nosqllist; for (int i=startRow;i<=rowCount;++i) { rowisrepeat = sheet.GetRow(i); if (rowisrepeat == null) continue; cellisrepeat = rowisrepeat.GetCell(13); string noisrpt = Convert.ToString(cellisrepeat); if (!NoList.Contains(noisrpt)) { NoList.Add(noisrpt); } else { msge = "編號:"+ noisrpt+"重復,插入失敗,請確定編號唯一、無重復!"; return dataTable; } } #endregion //填充行 for (int i = startRow; i <= rowCount; ++i) { row = sheet.GetRow(i); if (row == null) continue; dataRow = dataTable.NewRow(); for (int j = row.FirstCellNum; j < cellCount; ++j) { cell = row.GetCell(j); if (cell == null) { dataRow[j] = ""; } else { //CellType(Unknown = -1,Numeric = 0,String = 1,Formula = 2,Blank = 3,Boolean = 4,Error = 5,) switch (cell.CellType) { case CellType.Blank: dataRow[j] = ""; break; case CellType.Numeric: short format = cell.CellStyle.DataFormat; //對時間格式(2015.12.5、2015/12/5、2015-12-5等)的處理 if (format == 14 || format == 31 || format == 57 || format == 58) dataRow[j] = cell.DateCellValue; else dataRow[j] = cell.NumericCellValue; break; case CellType.String: dataRow[j] = cell.StringCellValue; break; } } } dataTable.Rows.Add(dataRow); } } } } } return dataTable; } catch (Exception e) { msge = e.Message; if (fs != null) { fs.Close(); } return null; } } /// <summary> /// 定義待驗證的Excel標題 /// </summary> /// <returns></returns> private static string[] GetStringNum() { string[] ExcelHeadList=new string[15] { "字段1", "字段2" , "字段3" , "字段4" , "字段5", "字段6","字段7", "字段8", "字段9", "字段10", "字段11", "字段12", "字段13", "字段14", "字段15" }; return ExcelHeadList; }