關於使用NPOI2.0 進行Excel導出的一些筆記

  1. 推薦使用2.0版本,雖然是beta版,但是至少支持office2007以上xlsx等後綴的文件。當讓,需要做好文檔不全的心理準備
  2. xls後綴文件使用HSSF包,xlsx使用XSSF包。ex,xlsx格式文件,實例化,IWorkbook exportFile = new XSSFWorkbook(templatePath);
  3. demo大部分使用CreateRow,CreateCell等方法,但是,這些方法是重新實例化,會覆蓋原有的單元格和列的屬性,比如背景色。請改用GetRow和GetCell方法。
  4. Workbook實例化(讀取現有excel模板等)消耗的時間可能會比較慢,也可能和我電腦配置渣有關。
  5. 單元格賦值的時候最好使用ToString()方式字符串賦值,因爲時間等類型不會自動轉換。
  6. 相比較而言,使用NPOI方式不需要服務器安裝office,不需要配置安全屬性,但是,個人還是更加喜歡用Office組件,因爲更加完善。

參考

demo
             bool ifSuccess = false ;
            string msg = "" ;
            string templatePath = Server.MapPath("\\Content\\template\\temp.xlsx" );
            string resultPath = "" ;
            try
            {
                resultPath = "\\Content\\template\\" + lCode + "_" + DateTime.Now.Second + ".xlsx";
                string savePath = Server.MapPath(resultPath);
                IWorkbook exportFile = new XSSFWorkbook(templatePath);

                ISheet sheet1 = exportFile.GetSheet("SheetName" );
                //int x = 1;
                //for (int i = 1; i <= 15; i++)
                //{
                //    IRow row = sheet1.CreateRow(i);
                //    for (int j = 0; j < 15; j++)
                //    {
                //        row.CreateCell(j).SetCellValue((x++).ToString());
                //    }
                //}
                IRow row = sheet1.CreateRow(3);
                row.CreateCell(0).SetCellValue("123");
                sheet1.GetRow(1).GetCell(1).SetCellValue(DateTime.Now.ToString());
                FileStream sw = System.IO.File .Create(savePath);
                exportFile.Write(sw);
                sw.Close();
                ifSuccess = true;
            }
            catch (Exception e)
            {
                msg = e.Message;
                if (e.InnerException != null )
                    msg += e.InnerException.Message;
            }


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章