1. 程式人生 > >Npoi匯出excel整理(附原始碼)

Npoi匯出excel整理(附原始碼)

http://www.cnblogs.com/WikStone/archive/2013/01/12/2857466.html

前些日子做了一個簡單的winform程式,需要匯出的功能,剛開始省事直接使用微軟的元件,但是匯出之後發現效率極其低下,絕對像web那樣使用npoi元件,因此簡單的進行了整理,包括直接根據DataTable匯出excel及DataGridview匯出excel,版本是1.2.4,下面貼下主要程式碼兩種方式,1、NPOI匯出excel、 2、普通的匯出excel

下面貼下主要程式碼:NPOI匯出

複製程式碼

     /// <summary>
         /// DataTable匯出到Excel檔案
         /// </summary>
         /// <param name="dtSource">源DataTable</param>
         /// <param name="strHeaderText">表頭文字</param>
         /// <param name="strFileName">儲存位置</param>
         public static void DataTableToExcel(DataTable dtSource, string strHeaderText, string strFileName)
         {
             using (MemoryStream ms = DataTableToExcel(dtSource, strHeaderText))
             {
                 using (FileStream fs = new FileStream(strFileName, FileMode.Create, FileAccess.Write))
                 {
                     byte[] data = ms.ToArray();
                     fs.Write(data, 0, data.Length);
                     fs.Flush();
                 }
             }
         }



/// <summary>
         /// DataTable匯出到Excel的MemoryStream
         /// </summary>
         /// <param name="dtSource">源DataTable</param>
         /// <param name="strHeaderText">表頭文字</param>
         public static MemoryStream DataTableToExcel(DataTable dtSource, string strHeaderText)
         {
             HSSFWorkbook workbook = new HSSFWorkbook();
             HSSFSheet sheet = (HSSFSheet)workbook.CreateSheet();
 
             #region 右擊檔案 屬性資訊
             {
                 DocumentSummaryInformation dsi = PropertySetFactory.CreateDocumentSummaryInformation();
                 dsi.Company = "NPOI";
                 workbook.DocumentSummaryInformation = dsi;
 
                 SummaryInformation si = PropertySetFactory.CreateSummaryInformation();
                 si.Author = "檔案作者資訊"; //填加xls檔案作者資訊
                 si.ApplicationName = "建立程式資訊"; //填加xls檔案建立程式資訊
                 si.LastAuthor = "最後儲存者資訊"; //填加xls檔案最後儲存者資訊
                 si.Comments = "作者資訊"; //填加xls檔案作者資訊
                 si.Title = "標題資訊"; //填加xls檔案標題資訊
                 si.Subject = "主題資訊";//填加檔案主題資訊
                 si.CreateDateTime = System.DateTime.Now;
                 workbook.SummaryInformation = si;
             }
             #endregion

             HSSFCellStyle dateStyle = (HSSFCellStyle)workbook.CreateCellStyle();
             HSSFDataFormat format = (HSSFDataFormat)workbook.CreateDataFormat();
             dateStyle.DataFormat = format.GetFormat("yyyy-mm-dd");
 
             //取得列寬
             int[] arrColWidth = new int[dtSource.Columns.Count];
             foreach (DataColumn item in dtSource.Columns)
             {
                 arrColWidth[item.Ordinal] = Encoding.GetEncoding(936).GetBytes(item.ColumnName.ToString()).Length;
             }
             for (int i = 0; i < dtSource.Rows.Count; i++)
             {
                 for (int j = 0; j < dtSource.Columns.Count; j++)
                 {
                     int intTemp = Encoding.GetEncoding(936).GetBytes(dtSource.Rows[i][j].ToString()).Length;
                     if (intTemp > arrColWidth[j])
                     {
                         arrColWidth[j] = intTemp;
                     }
                 }
             } 
             int rowIndex = 0; 
             foreach (DataRow row in dtSource.Rows)
             {
                 #region 新建表,填充表頭,填充列頭,樣式
                 if (rowIndex == 65535 || rowIndex == 0)
                 {
                     if (rowIndex != 0)
                     {
                         sheet = (HSSFSheet)workbook.CreateSheet();
                     }
 
                     #region 表頭及樣式
                     {
                         HSSFRow headerRow = (HSSFRow)sheet.CreateRow(0);
                         headerRow.HeightInPoints = 25;
                         headerRow.CreateCell(0).SetCellValue(strHeaderText);

                         HSSFCellStyle headStyle = (HSSFCellStyle)workbook.CreateCellStyle();
                       //  headStyle.Alignment = CellHorizontalAlignment.CENTER;
                         HSSFFont font = (HSSFFont)workbook.CreateFont();
                         font.FontHeightInPoints = 20;
                         font.Boldweight = 700;
                         headStyle.SetFont(font);
                         headerRow.GetCell(0).CellStyle = headStyle;
                        // sheet.AddMergedRegion(new Region(0, 0, 0, dtSource.Columns.Count - 1));
                         //headerRow.Dispose();
                     }
                     #endregion
 
 
                     #region 列頭及樣式
                     {
                         HSSFRow headerRow = (HSSFRow)sheet.CreateRow(1); 
                         HSSFCellStyle headStyle = (HSSFCellStyle)workbook.CreateCellStyle();
                         //headStyle.Alignment = CellHorizontalAlignment.CENTER;
                         HSSFFont font = (HSSFFont)workbook.CreateFont();
                         font.FontHeightInPoints = 10;
                         font.Boldweight = 700;
                         headStyle.SetFont(font); 
                         foreach (DataColumn column in dtSource.Columns)
                         {
                             headerRow.CreateCell(column.Ordinal).SetCellValue(column.ColumnName);
                             headerRow.GetCell(column.Ordinal).CellStyle = headStyle;
 
                             //設定列寬
                             sheet.SetColumnWidth(column.Ordinal, (arrColWidth[column.Ordinal] + 1) * 256); 
                         }
                        // headerRow.Dispose();
                     }
                     #endregion
 
                     rowIndex = 2;
                 }
                 #endregion
 
 
                 #region 填充內容
                 HSSFRow dataRow = (HSSFRow)sheet.CreateRow(rowIndex);
                 foreach (DataColumn column in dtSource.Columns)
                 {
                     HSSFCell newCell =(HSSFCell) dataRow.CreateCell(column.Ordinal);
 
                     string drValue = row[column].ToString();
 
                     switch (column.DataType.ToString())
                     {
                         case "System.String"://字串型別
                             newCell.SetCellValue(drValue);
                             break;
                         case "System.DateTime"://日期型別
                            System.DateTime dateV;
                            System.DateTime.TryParse(drValue, out dateV);
                             newCell.SetCellValue(dateV);
 
                             newCell.CellStyle = dateStyle;//格式化顯示
                             break;
                         case "System.Boolean"://布林型
                             bool boolV = false;
                             bool.TryParse(drValue, out boolV);
                             newCell.SetCellValue(boolV);
                             break;
                         case "System.Int16"://整型
                         case "System.Int32":
                         case "System.Int64":
                         case "System.Byte":
                             int intV = 0;
                             int.TryParse(drValue, out intV);
                             newCell.SetCellValue(intV);
                             break;
                         case "System.Decimal"://浮點型
                         case "System.Double":
                             double doubV = 0;
                             double.TryParse(drValue, out doubV);
                             newCell.SetCellValue(doubV);
                             break;
                         case "System.DBNull"://空值處理
                             newCell.SetCellValue("");
                             break;
                         default:
                             newCell.SetCellValue("");
                             break;
                     }
 
                 }
                 #endregion
 
                 rowIndex++;
             } 
             using (MemoryStream ms = new MemoryStream())
             {
                 workbook.Write(ms);
                 ms.Flush();
                 ms.Position = 0;
 
                 sheet.Dispose();
                 //workbook.Dispose();//一般只用寫這一個就OK了,他會遍歷並釋放所有資源,但當前版本有問題所以只釋放sheet
                 return ms;
             } 
         }

複製程式碼

普通excel匯出

複製程式碼

#region 匯出excel

       public static void ExportExcel(string fileName, DataGridView myDGV,bool isShowDialog)
       {
           string saveFileName = "";
           if (isShowDialog)
           {
               //bool fileSaved = false;
               SaveFileDialog saveDialog = new SaveFileDialog();
               saveDialog.DefaultExt = "xls";
               saveDialog.Filter = "Excel檔案|*.xls";
               saveDialog.FileName = fileName;
               saveDialog.ShowDialog();
               saveFileName = saveDialog.FileName;
               if (saveFileName.IndexOf(":") < 0) return; //被點了取消 
           }
           else
           {
              // saveFileName = Application.StartupPath + @"\匯出記錄\" + fileName + ".xls";
               saveFileName = fileName;
           }
           Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();
           if (xlApp == null)
           {
               MessageBox.Show("無法建立Excel物件,可能您的機子未安裝Excel");
               return;
           }

           Microsoft.Office.Interop.Excel.Workbooks workbooks = xlApp.Workbooks;
           Microsoft.Office.Interop.Excel.Workbook workbook = workbooks.Add(Microsoft.Office.Interop.Excel.XlWBATemplate.xlWBATWorksheet);
           Microsoft.Office.Interop.Excel.Worksheet worksheet = (Microsoft.Office.Interop.Excel.Worksheet)workbook.Worksheets[1];//取得sheet1 

           //寫入標題
           for (int i = 0; i < myDGV.ColumnCount; i++)
           {
               worksheet.Cells[1, i + 1] = myDGV.Columns[i].HeaderText;
           }
           //寫入數值
           for (int r = 0; r < myDGV.Rows.Count; r++)
           {
               for (int i = 0; i < myDGV.ColumnCount; i++)
               {
                   if (myDGV[i, r].ValueType == typeof(string)
                      || myDGV[i, r].ValueType == typeof(DateTime))//這裡就是驗證DataGridView單元格中的型別,如果是string或是DataTime型別,則在放入緩 存時在該內容前加入" ";
                   {
                       worksheet.Cells[r + 2, i + 1] = "'" + myDGV.Rows[r].Cells[i].Value;
                   }
                   else
                   {
                       worksheet.Cells[r + 2, i + 1] = myDGV.Rows[r].Cells[i].Value;
                   }
               }
               System.Windows.Forms.Application.DoEvents();
           }
           worksheet.Columns.EntireColumn.AutoFit();//列寬自適應
           //if (Microsoft.Office.Interop.cmbxType.Text != "Notification")
           //{
           //    Excel.Range rg = worksheet.get_Range(worksheet.Cells[2, 2], worksheet.Cells[ds.Tables[0].Rows.Count + 1, 2]);
           //    rg.NumberFormat = "00000000";
           //}

           if (saveFileName != "")
           {
               try
               {
                   workbook.Saved = true;
                   workbook.SaveCopyAs(saveFileName);
                   //fileSaved = true;
               }
               catch (Exception ex)
               {
                   //fileSaved = false;
                   MessageBox.Show("匯出檔案時出錯,檔案可能正被開啟!\n" + ex.Message);
               }

           }
           //else
           //{
           //    fileSaved = false;
           //}
           xlApp.Quit();
           GC.Collect();//強行銷燬 
           // if (fileSaved && System.IO.File.Exists(saveFileName)) System.Diagnostics.Process.Start(saveFileName); //開啟EXCEL
           MessageBox.Show(fileName + "儲存成功", "提示", MessageBoxButtons.OK);
       }

       #endregion

複製程式碼

5萬條資料效能測試

下面附上原始碼,裡面有NPOI和普通匯出excel的效能比較。

下載原始碼 如果您覺的文章不錯,請點選推薦!