NPOI導入導出Excel

一、簡介

       NPOI是一個開源的C#讀寫Excel、Word等微軟OLE2組件文檔的項目,可以在沒有安裝Office的情況下對Word或Excel文檔進行導入導出操作。

      官網:http://npoi.codeplex.com/

二、相關引用

      1.ICsharpcode.SharpZipLib.dll      對文件進行壓縮、解壓操作,支持Zip, GZip, BZip2 和Tar格式

      2.NPOI.dll                                      微軟Excel BIFF(Excel 97-2003, doc)格式讀寫庫,基礎類庫

      3.NPOI.OOXML.dll                        Excel 2007(xlsx)格式讀寫庫,Word 2007(docx)格式讀寫庫

      4.NPOI.OpenXml4Net.dll              OpenXml底層zip包讀寫庫

      5.NPOI.OpenXmlFormats.dll         微軟Office OpenXml對象關係庫

三、導入Excel實例

      1.新建一個類,命名爲ExcelHelper。

      2.添加引用:using NPOI.HSSF.UserModel;(Excel 97-2003, doc)格式讀寫庫
                           using NPOI.SS.UserModel;Excel公用接口及Excel公式計算引擎
                           using NPOI.XSSF.UserModel;Excel 2007(xlsx)格式讀寫庫

      3.添加ExcelToTable方法

        /// <summary>
        /// 讀取Excel
        /// </summary>
        /// <param name="file">文件全路徑</param>
        /// <param name="sheetName">excel表sheet名稱</param>
        /// <returns>返回DaTaTable</returns>
        public static DataTable ExcelToTable(string file, string sheetName = null)
        {
            DataTable dt = new DataTable();
            try
            {
                using (FileStream fs = new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.Read))//打開excel文件
                {
                    IWorkbook workbook = null;
                    if (file.IndexOf(".xlsx") > 0) // 2007版本
                        workbook = new XSSFWorkbook(fs);
                    else if (file.IndexOf(".xls") > 0) // 2003版本
                        workbook = new HSSFWorkbook(fs);

                    ISheet sheet = null;
                    if (sheetName == null)
                        sheet = workbook.GetSheetAt(0);//根據座標讀區sheet表,0表示第一個
                    else
                        sheet = workbook.GetSheet(sheetName);//根據sheet名稱讀取sheet表

                    //列名
                    IRow rowHead = sheet.GetRow(sheet.FirstRowNum);//sheet.FirstRowNum 第一個單元格的行號
                    for (int i = 0; i < rowHead.LastCellNum; i++)//rowHead.LastCellNum 最後一個單元格的列號
                    {
                        string fildName = rowHead.GetCell(i).StringCellValue;
                        dt.Columns.Add(fildName, typeof(String));
                    }

                    //數據
                    for (int i = sheet.FirstRowNum + 1; i <= sheet.LastRowNum; i++)//sheet.LastRowNum最後一個單元格的行號
                    {
                        IRow row = sheet.GetRow(i);
                        DataRow dr = dt.NewRow();
                        for (int j = row.FirstCellNum; j < row.LastCellNum; j++)
                        {
                            ICell cell = row.GetCell(j);
                            dr[j] = GetValueType(cell);
                            if (dr[j] == null)
                            {
                                break;
                            }
                        }
                        dt.Rows.Add(dr);
                    }
                }
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
            return dt;
        }

      4.添加GetValueType方法

        /// <summary>  
        /// 獲取單元格類型(xlsx)  
        /// </summary>  
        /// <param name="cell"></param>  
        /// <returns></returns>  
        private static object GetValueType(ICell cell)
        {
            try
            {
                //XSSFCell
                if (cell == null)
                {
                    return null;
                }
                switch (cell.CellType)
                {
                    case NPOI.SS.UserModel.CellType.Blank: //BLANK:  
                        return null;
                    case NPOI.SS.UserModel.CellType.Boolean: //BOOLEAN:  
                        return cell.BooleanCellValue;
                    case NPOI.SS.UserModel.CellType.Numeric: //NUMERIC:  
                        return cell.NumericCellValue;
                    case NPOI.SS.UserModel.CellType.String: //STRING:  
                        return cell.StringCellValue;
                    case NPOI.SS.UserModel.CellType.Error: //ERROR:  
                        return cell.ErrorCellValue;
                    case NPOI.SS.UserModel.CellType.Formula: //FORMULA:  
                    default:
                        return "=" + cell.CellFormula;
                }
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }

四、導出Excel實例

        1、添加Export方法

        /// <summary>   
        /// DataTable導出到Excel的MemoryStream   
        /// </summary>   
        /// <param name="dtSource">源DataTable</param>   
        /// <param name="strHeaderText">表頭文本</param>   
        public static MemoryStream Export(DataTable dtSource, string strHeaderText)
        {
            HSSFWorkbook workbook = new HSSFWorkbook();
            HSSFSheet sheet = workbook.CreateSheet("Sheet1");//創建一張sheet表

            #region 生成的excel文件,右擊文件 屬性信息,可以去掉
            {
                DocumentSummaryInformation dsi = PropertySetFactory.CreateDocumentSummaryInformation();
                dsi.Company = "http://www.baidu.com/";
                workbook.DocumentSummaryInformation = dsi;

                SummaryInformation si = PropertySetFactory.CreateSummaryInformation();
                si.Author = ""; //填加xls文件作者信息   
                si.ApplicationName = "NPOI測試程序"; //填加xls文件創建程序信息   
                si.LastAuthor = ""; //填加xls文件最後保存者信息   
                si.Comments = "說明信息"; //填加xls文件作者信息   
                si.Title = "NPOI測試"; //填加xls文件標題信息   
                si.Subject = "NPOI測試Demo";//填加文件主題信息   
                si.CreateDateTime = DateTime.Now;
                workbook.SummaryInformation = si;
            }
            #endregion

            HSSFCellStyle dateStyle = workbook.CreateCellStyle();//設置單元格樣式
            HSSFDataFormat format = 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)//excel表2003及之前最大行數65536,2007後最大1048576行
                {
                    if (rowIndex != 0)
                    {
                        sheet = workbook.CreateSheet();//創建一張sheet表
                    }

                    #region 表頭及樣式
                    {
                        HSSFRow headerRow = sheet.CreateRow(0);//設置首行
                        headerRow.HeightInPoints = 25;//設置高
                        headerRow.CreateCell(0).SetCellValue(strHeaderText);//設置表頭文本

                        HSSFCellStyle headStyle = workbook.CreateCellStyle();//設置單元格樣式
                        // headStyle.Alignment = CellHorizontalAlignment.CENTER;
                        HSSFFont font = 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));//合併單元格
                    }
                    #endregion
                    #region 列頭及樣式
                    {
                        HSSFRow headerRow = sheet.CreateRow(1);
                        
                        HSSFCellStyle headStyle = workbook.CreateCellStyle();
                        HSSFFont font = 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);
                        }
                    }
                    #endregion

                    rowIndex = 2;
                }
                #endregion
                
                #region 填充內容
                HSSFRow dataRow = sheet.CreateRow(rowIndex);
                foreach (DataColumn column in dtSource.Columns)
                {
                    HSSFCell newCell = dataRow.CreateCell(column.Ordinal);
                    string drValue = row[column].ToString();
                    switch (column.DataType.ToString())
                    {
                        case "System.String"://字符串類型   
                            newCell.SetCellValue(drValue);
                            break;
                        case "System.DateTime"://日期類型   
                            DateTime dateV;
                            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;
                return ms;
            }

        }

        2、添加ExportByWeb方法

        /// <summary>   
        /// 用於Web導出   
        /// </summary>   
        /// <param name="dtSource">源DataTable</param>   
        /// <param name="strHeaderText">表頭文本</param>   
        /// <param name="strFileName">文件名</param>   
        public static void ExportByWeb(DataTable dtSource, string strHeaderText, string strFileName)
        {

            HttpContext curContext = HttpContext.Current;
            // 設置編碼和附件格式   
            curContext.Response.ContentType = "application/vnd.ms-excel";
            curContext.Response.ContentEncoding = Encoding.UTF8;
            curContext.Response.Charset = "";
            curContext.Response.AppendHeader("Content-Disposition",
                "attachment;filename=" + HttpUtility.UrlEncode(strFileName, Encoding.UTF8));

            curContext.Response.BinaryWrite(Export(dtSource, strHeaderText).GetBuffer());//調用上面的Export方法
            curContext.Response.End();

        }

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