NPOI

2018-06-17 19:28:01来源:未知 阅读 ()

新老客户大回馈,云服务器低至5折

前言:

         NPOI 技术在别人看来可能有点老生长谈了,但是对于我现在处于的这个创业型公司,还是挺前沿的,不知道是前辈们不知道这个技术,还是懒得去对现有的软件进行修改,因为在现有的软件中,几乎所有的数据导入导出都是依赖于:

        Excel.Application(设置excel组件,系统权限,然后还得考虑版本一系列的问题)都是

        基于现有的方法,之前的技术团队在软件没有推广之前可能自我感觉良好,没有进行一些系统性的测试,在加上一些别的因素吧,导致在工程文件中对 Excel.Application 的操作方法,操作类层出不穷,算了,不揭短了。

        有的时候向领导提出想对项目框架优化,或者对代码的优化有所动作的时候,总会有层出不穷的原因导致这个动作渐渐的滞后。这只是一个点,可想而知在没有一个真正的技术经理参与的项目中,没有对框架优化,方法重构的发起人,本来不是很复杂的项目,代码的臃肿,堪忧。

 

算了,不吐槽了,可能是好久没有写博的原因。哭泣的脸

数据输出方法:

    /// <summary>
    /// 携带数据导出
     /// </summary>
    /// <param name="dtSource"></param>
    /// <param name="_excelName"></param>
    /// <param name="str_fieldtext"></param>
    public void export(DataTable dtSource, string _excelName, string str_fieldtext)
    {
        HttpContext curContext = HttpContext.Current;
        // 设置编码和附件格式
        curContext.Response.ContentType = "application/ms-excel";
        curContext.Response.ContentEncoding = Encoding.UTF8;
        curContext.Response.Charset = "";
        string fileName = _excelName + DateTime.Now.ToString("yyyyMMddHHmmss") + ".xls"; //Excel文件名称
        curContext.Response.AppendHeader("Content-Disposition",
            "attachment;filename=" + HttpUtility.UrlEncode(fileName, Encoding.UTF8));
        //调用导出具体方法Export()
        curContext.Response.BinaryWrite(Export(dtSource, _excelName, str_fieldtext).GetBuffer());
        curContext.Response.End();
    }

导出方法:

#region DataTable导出到Excel
    /// <summary>
    /// DataTable导出到Excel的MemoryStream Export()
    /// </summary>
    /// <param name="dtSource">DataTable数据源</param>
    /// <param name="strHeaderText">Excel表头文本</param>
    /// <param name="str_fieldtext"></param> 
    public static MemoryStream Export(DataTable dtSource, string strHeaderText, string str_fieldtext)
    {
        HSSFWorkbook workbook = new HSSFWorkbook();

        ISheet sheet = workbook.CreateSheet("Data");

        ISheet sheet2 = workbook.CreateSheet("ShtDictionary");

        //sheet.DisplayGridlines = false;//隐藏网格线

        #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

        ICellStyle dateStyle = workbook.CreateCellStyle();

        IDataFormat 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)
            {
                if (rowIndex != 0)
                {
                    sheet = workbook.CreateSheet();
                }

                #region 表头及样式
                {
                    //IRow headerRow = sheet.CreateRow(0);

                    //headerRow.HeightInPoints = 25;

                    //headerRow.CreateCell(0).SetCellValue(strHeaderText);

                    //ICellStyle headStyle = workbook.CreateCellStyle();

                    //headStyle.Alignment = HorizontalAlignment.Center;

                    //IFont font = workbook.CreateFont();

                    //font.FontHeightInPoints = 20;

                    //font.Boldweight = 700;

                    //headStyle.SetFont(font);

                    //headerRow.GetCell(0).CellStyle = headStyle;

                    //sheet.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(0, 0, 0, dtSource.Columns.Count - 1));
                }
                #endregion

                #region 列头及样式
                {
                    IRow headerRow = sheet.CreateRow(0);

                    ICellStyle headStyle = workbook.CreateCellStyle();

                    headStyle.Alignment = HorizontalAlignment.Center;

                    IFont font = workbook.CreateFont();

                    font.FontHeightInPoints = 10;

                    font.Boldweight = 700;

                    headStyle.SetFont(font);

                    headStyle.FillPattern = FillPattern.SolidForeground;

                    headStyle.FillForegroundColor = NPOI.HSSF.Util.HSSFColor.Yellow.Index2;//单元格背景色

                    HSSFPatriarch patr = sheet.CreateDrawingPatriarch() as HSSFPatriarch;

                    HSSFClientAnchor a = new HSSFClientAnchor();

                    a.Dx1 = 0;

                    a.Dy1 = 0;

                    a.Dx2 = 0;

                    a.Dy2 = 0;

                    int colindex = 27;
                    string[] str_text = { };
                    if (str_fieldtext.Length > 0)
                    {
                        str_text = str_fieldtext.Split(',');
                    }
                    foreach (DataColumn column in dtSource.Columns)
                    {
                        a.Col1 = column.Ordinal + 1;//批注起始位置的纵坐标(当前单元格位置+2)  

                        a.Col2 = column.Ordinal + 3;//批注结束位置的纵坐标  

                        a.Row1 = column.Ordinal + 0;//批注起始位置的横坐标  

                        a.Row2 = column.Ordinal + 4;//批注结束位置的横坐标  

                        HSSFComment co = patr.CreateComment(a);//实例化批注模型

                        co.String = new HSSFRichTextString(Convert.ToString(column.ColumnName));//批注内容

                        co.Author = "XX软件";//批注者
                        if (str_text.Length > 0)
                            headerRow.CreateCell(column.Ordinal).SetCellValue(str_text[column.Ordinal]);//添加单元格内容
                        else
                            headerRow.CreateCell(column.Ordinal).SetCellValue(column.ColumnName);//添加单元格内容
                        headerRow.GetCell(column.Ordinal).CellComment = co;//在该单元格是那个添加批注

                        headerRow.GetCell(column.Ordinal).CellStyle = headStyle;//给该单元格添加样式

                        sheet.SetColumnWidth(column.Ordinal, (arrColWidth[column.Ordinal] + 1) * 256);//设置列宽

                        #region 冻结
                        ///下面对CreateFreezePane的参数作一下说明:
                        ///第一个参数表示要冻结的列数;
                        ///第二个参数表示要冻结的行数,这里只冻结列所以为0;
                        ///第三个参数表示右边区域可见的首列序号,从1开始计算;
                        ///第四个参数表示下边区域可见的首行序号,也是从1开始计算,这里是冻结列,所以为0;
                        //sheet.CreateFreezePane(1, 0, 1, 0);//冻结首列

                        sheet.CreateFreezePane(0, 1, 0, 1);//冻结首行
                        #endregion

                        #region 下拉

                        //if (column.Ordinal == 0)
                        //{
                        //    sheet2.CreateRow(0).CreateCell(0).SetCellValue("itemA");

                        //    sheet2.CreateRow(1).CreateCell(0).SetCellValue("itemB");

                        //    sheet2.CreateRow(2).CreateCell(0).SetCellValue("itemC");
                        //}
                        //else
                        //{
                        //    sheet2.GetRow(0).CreateCell(column.Ordinal).SetCellValue("itemA" + column.Ordinal + "");

                        //    sheet2.GetRow(1).CreateCell(column.Ordinal).SetCellValue("itemB" + column.Ordinal + "");

                        //    sheet2.GetRow(2).CreateCell(column.Ordinal).SetCellValue("itemC" + column.Ordinal + "");
                        //}

                        //string colname = string.Empty;

                        //int remainder = 0;

                        //remainder = colindex % 26;

                        //if (remainder == 0) remainder = 26;

                        //colname = Convert.ToString((char)(remainder + 64));

                        //IName range = workbook.CreateName();

                        //range.RefersToFormula = string.Format("{0}!$" + colname + "$1:$" + colname + "${1}", "ShtDictionary", 3);

                        //range.NameName = "dicRange" + column.Ordinal + "";

                        //ISheet sheet1 = workbook.GetSheet("Data");
                        ////碰对了,第四个参数确定每次的下拉放到哪个column.Ordinal列,因缺思停
                        //CellRangeAddressList regions = new CellRangeAddressList(0, 65535, 0, column.Ordinal);

                        //DVConstraint constraint = DVConstraint.CreateFormulaListConstraint("dicRange" + column.Ordinal + "");

                        //HSSFDataValidation dataValidate = new HSSFDataValidation(regions, constraint);

                        //sheet1.AddValidationData(dataValidate);

                        //colindex++;

                        #endregion
                    }
                }
                #endregion

                rowIndex = 1;
            }
            #endregion

            #region 填充内容

            IRow dataRow = sheet.CreateRow(rowIndex);

            foreach (DataColumn column in dtSource.Columns)
            {
                ICell newCell = 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;
            return ms;
        }
    }
    #endregion

读取excel 数据:

    /// <summary>
    /// 读取excel ,默认第一行为标头(获取DataTable)
    /// </summary>
    /// <param name="strFileName">excel文档路径</param>
    /// <returns></returns>
    public DataTable Import(string strFileName)
    {
        DataTable dt = new DataTable();

        HSSFWorkbook hssfworkbook;

        using (FileStream file = new FileStream(strFileName, FileMode.Open, FileAccess.Read))
        {
            hssfworkbook = new HSSFWorkbook(file);
        }
        ISheet sheet = hssfworkbook.GetSheetAt(0);
        System.Collections.IEnumerator rows = sheet.GetRowEnumerator();

        IRow headerRow = sheet.GetRow(0);
        int cellCount = headerRow.LastCellNum;

        for (int j = 0; j < cellCount; j++)
        {
            ICell cell = headerRow.GetCell(j);
            dt.Columns.Add(cell.ToString());
        }

        for (int i = (sheet.FirstRowNum + 1); i <= sheet.LastRowNum; i++)
        {
            IRow row = sheet.GetRow(i);
            DataRow dataRow = dt.NewRow();

            for (int j = row.FirstCellNum; j < cellCount; j++)
            {
                if (row.GetCell(j) != null)
                {
                    if (row.GetCell(j).ToString().Contains('/'))
                    {
                        string[] a = row.GetCell(j).ToString().Split('/');

                        dataRow[j] = "20" + a[2] + "-" + a[0] + "-" + a[1];
                    }
                    else
                    {
                        dataRow[j] = row.GetCell(j).ToString();
                    }
                }
                else
                {
                    dataRow[j] = null;
                }
            }

            dt.Rows.Add(dataRow);
        }
        return dt;
    }

换一种方式:

    /// <summary>
    /// 导出excel 模板
     /// </summary>
    /// <param name="str_fieldid"></param>
    /// <param name="str_fieldtext"></param>
    /// <returns></returns>
    public void export(string _excelName, string str_fieldid, string str_fieldtext)
    {
        HSSFWorkbook workbook = new HSSFWorkbook();

        ISheet sheet = workbook.CreateSheet("Data");

        #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

        ICellStyle dateStyle = workbook.CreateCellStyle();

        IDataFormat format = workbook.CreateDataFormat();

        dateStyle.DataFormat = format.GetFormat("yyyy-mm-dd");

        int rowIndex = 0;

        #region 新建表,填充表头,填充列头,样式
        if (rowIndex == 65535 || rowIndex == 0)
        {
            if (rowIndex != 0)
            {
                sheet = workbook.CreateSheet();
            }

            #region 列头及样式
            {
                IRow headerRow = sheet.CreateRow(0);

                ICellStyle headStyle = workbook.CreateCellStyle();

                headStyle.Alignment = HorizontalAlignment.Center;

                IFont font = workbook.CreateFont();

                font.FontHeightInPoints = 10;

                font.Boldweight = 700;

                headStyle.SetFont(font);

                headStyle.FillPattern = FillPattern.SolidForeground;

                headStyle.FillForegroundColor = NPOI.HSSF.Util.HSSFColor.Yellow.Index2;//单元格背景色

                HSSFPatriarch patr = sheet.CreateDrawingPatriarch() as HSSFPatriarch;

                HSSFClientAnchor a = new HSSFClientAnchor();

                a.Dx1 = 0;

                a.Dy1 = 0;

                a.Dx2 = 0;

                a.Dy2 = 0;

                string[] str_text = { };

                string[] str_field = { };

                if (str_fieldtext.Length > 0)
                {
                    str_text = str_fieldtext.Split(',');
                }

                if (str_fieldid.Length > 0)
                {
                    str_field = str_fieldid.Split(',');
                }

                //取得列宽
                int[] arrColWidth = new int[str_text.Length];

                for (int i = 0; i < str_text.Length; i++)
                {
                    a.Col1 = i + 1;//批注起始位置的纵坐标(当前单元格位置+2)  

                    a.Col2 = i + 3;//批注结束位置的纵坐标  

                    a.Row1 = i + 0;//批注起始位置的横坐标  

                    a.Row2 = i + 4;//批注结束位置的横坐标  

                    HSSFComment co = patr.CreateComment(a);//实例化批注模型

                    co.String = new HSSFRichTextString(Convert.ToString(str_field[i]));//批注内容

                    co.Author = "XX软件";//批注者
                    if (str_text.Length > 0)
                        headerRow.CreateCell(i).SetCellValue(str_text[i]);//添加单元格内容
                    else
                        headerRow.CreateCell(i).SetCellValue(str_field[i]);//添加单元格内容
                    headerRow.GetCell(i).CellComment = co;//在该单元格是那个添加批注

                    headerRow.GetCell(i).CellStyle = headStyle;//给该单元格添加样式

                    sheet.SetColumnWidth(i, 20 * 256);//设置列宽

                    //sheet.SetColumnWidth(i, 250);

                    #region 冻结

                    sheet.CreateFreezePane(0, 1, 0, 1);//冻结首行

                    #endregion
                }
            }
            #endregion

            rowIndex = 1;
        }
        #endregion

        using (MemoryStream ms = new MemoryStream())
        {
            workbook.Write(ms);
            ms.Flush();
            ms.Position = 0;
            ExportOut(ms, _excelName);
        }
    }

    /// <summary>
    /// 输出方法
    /// </summary>
    /// <param name="ms"></param>
    /// <param name="_excelName"></param>
    public void ExportOut(MemoryStream ms, string _excelName)
    {
        HttpContext curContext = HttpContext.Current;
        // 设置编码和附件格式
         curContext.Response.ContentType = "application/ms-excel";
        curContext.Response.ContentEncoding = Encoding.UTF8;
        curContext.Response.Charset = "";
        string fileName = _excelName + DateTime.Now.ToString("yyyyMMddHHmmss") + ".xls"; //Excel文件名称
          curContext.Response.AppendHeader("Content-Disposition",
            "attachment;filename=" + HttpUtility.UrlEncode(fileName, Encoding.UTF8));
        //调用导出具体方法Export()
        curContext.Response.BinaryWrite(ms.GetBuffer());
        curContext.Response.End();
    }

NPOI组件:    http://files.cnblogs.com/files/houlin/NPOI.zip

 

后言:

以上就是一些方法来自园子里好多前辈的博文,我自己没有做什么优化,目前只做记录,备忘,不喜勿喷。

 

标签:

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有

上一篇:微软企业库之数据访问模块基本使用

下一篇:Nancy之给我们的网站添加自定义图标