(C#)使用NPOI導出Excel


  在做業務型的軟件時,經常需要將某些數據導出,本文介紹了在Winform或Asp.net中使用NPOI(POI 項目的 .NET 版本)來操作Excel文件,而無需安裝Office。

  首先,需要獲取NPOI組件

  其次,讓你的網站或類庫添加NPOI引用。對於導出導入Excel來說,需要引用的dll文件有:

  NPOI.dll,NPOI.HSSF.dll,NPOI.POIFS.dll

  最后,在網站或類庫中新建一個導出幫助類,例如命名為ExcelHelper.cs

ExcelHelper.cs

public class ExportHelper
    {
        public static Stream RenderDataTableToExcel(DataTable SourceTable)
        {
            HSSFWorkbook workbook = new HSSFWorkbook();
            MemoryStream ms = new MemoryStream();
            HSSFSheet sheet = workbook.CreateSheet();
            HSSFRow headerRow = sheet.CreateRow(0);

            // handling header. 
            foreach (DataColumn column in SourceTable.Columns)
                headerRow.CreateCell(column.Ordinal).SetCellValue(column.ColumnName);

            // handling value. 
            int rowIndex = 1;

            foreach (DataRow row in SourceTable.Rows)
            {
                HSSFRow dataRow = sheet.CreateRow(rowIndex);

                foreach (DataColumn column in SourceTable.Columns)
                {
                    dataRow.CreateCell(column.Ordinal).SetCellValue(row[column].ToString());
                }

                rowIndex++;
            }

            workbook.Write(ms);
            ms.Flush();
            ms.Position = 0;

            sheet = null;
            headerRow = null;
            workbook = null;

            return ms;
        }
        public static DataTable RenderDataTableFromExcel(Stream ExcelFileStream, int SheetIndex, int HeaderRowIndex)
        {
            HSSFWorkbook workbook = new HSSFWorkbook(ExcelFileStream);
            HSSFSheet sheet = workbook.GetSheetAt(SheetIndex);

            DataTable table = new DataTable();

            HSSFRow 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);
            }

            int rowCount = sheet.LastRowNum;

            for (int i = (sheet.FirstRowNum + 1); i <= sheet.LastRowNum; i++)
            {
                HSSFRow 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;
        }
    }

 

在方法中調用ExcelHelper:

  

  示例1:導出Excel:

protected void exportExcelFun(){
        DataTable dt=new DataTable();
        dt=XXXXX;//Use ADO.NET to get Data from DB
        MemoryStream ms = ExportHelper.RenderDataTableToExcel(dt) as MemoryStream;
        
        /*情況1:在Asp.NET中,輸出文件流,瀏覽器自動提示下載*/
        Response.AddHeader("Content-Disposition", string.Format("attachment; filename=download.xls")); Response.BinaryWrite(ms.ToArray()); ms.Close(); ms.Dispose(); 

        /*情況2:在Winform中,彈出SaveFileDialog,提示用戶選擇文件放置位置。*/
        
         string saveFileName = "";
         bool fileSaved = false;
         SaveFileDialog saveDialog = new SaveFileDialog();
         saveDialog.DefaultExt = "xls";
         saveDialog.Filter = "Excel文件|*.xls";
         saveDialog.FileName = "download";
         saveDialog.ShowDialog();
         saveFileName = saveDialog.FileName;
         if (saveFileName.IndexOf(":") < 0) return; //被點了取消
         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("導出文件時出錯,文件可能正被打開!\n" + ex.Message);
                }
          }
          else{
                fileSaved = false;
          }
          GC.Collect();//強行銷毀
          if (fileSaved && File.Exists(saveFileName)){
              MessageBox.Show("導出成功!", "通知");
          }
          else {
                 MessageBox.Show("導出失敗!", "通知");
          }
}               

  

  示例2:導入Excel

protected void importExcelFun(){
    /*情況1:在Asp.net網站,一般使用asp:FileUpLoad控件(實際上是一個HTML表單.input:type=file)上傳文件*/
    if(this.FileUpLoader.HasFile){
        DataTable dt=new DataTable();
     //設置第1行為標題行,從第二行開始讀取數據。標題行作為DataTable表頭。 dt
=ExcelHelper.RenderDataTableFromExcel(this.FileUpLoader.FileContent,0,0);
     
//use dt to do something } /*情況2:在Winform中,*/ OpenFileDialog fileDialog = new OpenFileDialog(); fileDialog.Filter = "Excel文件|*.xls"; fileDialog.InitialDirectory = "E:\\";//設置默認打開路徑 if (fileDialog.ShowDialog() == DialogResult.OK){ string fileName=fileDialog.FileName;//得到文件所在位置。
     
// use c# to read Excel File as Steam.
     // use ExcelHelper for converting Stream to DataTable.
} }

  有的工具或方式導出的Excel文件非標准文件,只可用於閱讀,而無法進行其它業務操作。

  而使用NPOI導出的Excel文件均為標准格式,與Windows下人工創建的Excel文件完全一致。

  (完)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM