Web开发工作中经常要根据业务的需要生成对应的报表。经常采用的方法如下:

  • 将DataTable导出至Excel文件;
  • 读取模板Excel文件;
  • 修改模板Excel文件对应的内容。

因此,便想到封装一个基于NPOI的Excel操作类(至于为什么不用Excel组件,那是因为Excel组件效率低且必须安装Office),所完成的功能大致如上所示,这样平时的报表开发效率就比原来高效很多。

首先是DataTable导出至Excel文件,代码关键部分有注释说明,具体代码如下所示:

/// <summary>
        /// 从DataTable中将数据导出到Excel文件
        /// </summary>
        /// <param name="dtSource">提供导出数据的DataTable</param>
        /// <param name="headerText">表头文本</param>
        /// <returns></returns>
        public static MemoryStream ExportDataTable(DataTable dtSource, string headerText)
        {
            //创建工作表
            var workbook = new HSSFWorkbook();
            //创建sheet页
            var sheet = workbook.CreateSheet();
            #region 添加Excel文件属性信息

            var dsi = PropertySetFactory.CreateDocumentSummaryInformation();
            dsi.Company = "ZWKJ";
            workbook.DocumentSummaryInformation = dsi;

            var si = PropertySetFactory.CreateSummaryInformation();
            si.Author = "鞠小军";
            si.ApplicationName = "使用NPOI创建的Excel文件";
            si.CreateDateTime = DateTime.Now;
            workbook.SummaryInformation = si;

            #endregion

            //设置日期格式
            var dateStyle = workbook.CreateCellStyle();
            var format = workbook.CreateDataFormat();
            dateStyle.DataFormat = format.GetFormat("yyyy-mm-dd");
            //取得列宽
            var columnWidth = new int[dtSource.Columns.Count];
            //遍历DataTable的列
            foreach (DataColumn column in dtSource.Columns)
            {
                columnWidth[column.Ordinal] = Encoding.GetEncoding().GetBytes(column.ColumnName).Length;
            }
            //遍历所有的Row,若当前Row内容长度超出列名长度,则将此列的长度设为该Row内容长度
            ; i < dtSource.Rows.Count; i++)
            {
                ; j < dtSource.Columns.Count; j++)
                {
                    ).GetBytes(dtSource.Rows[i][j].ToString()).Length;
                    if (currentRowLength > columnWidth[j])
                        columnWidth[j] = currentRowLength;
                }
            }

            ;
            #region 表头及样式

            );
            headRow.HeightInPoints = ;
            headRow.CreateCell().SetCellValue(headerText);

            var headStyle = workbook.CreateCellStyle();
            headStyle.Alignment = HorizontalAlignment.CENTER;
            var font = workbook.CreateFont();
            font.Boldweight = ;
            font.FontHeightInPoints = ;
            headStyle.SetFont(font);
            headRow.GetCell().CellStyle = headStyle;
            sheet.AddMergedRegion(, , , dtSource.Columns.Count - ));
            #endregion
            #region 列头及样式

            );
            var columnStyle = workbook.CreateCellStyle();
            columnStyle.Alignment = HorizontalAlignment.CENTER;
            var columnFont = workbook.CreateFont();
            columnFont.Boldweight = ;
            columnFont.FontHeightInPoints = ;
            columnStyle.SetFont(columnFont);
            foreach (DataColumn column in dtSource.Columns)
            {
                //设置列头内容
                columnRow.CreateCell(column.Ordinal).SetCellValue(column.ColumnName);
                //设置列头样式
                columnRow.GetCell(column.Ordinal).CellStyle = columnStyle;
                //设置列宽
                sheet.SetColumnWidth(column.Ordinal, (columnWidth[column.Ordinal] + ) * );

            }
            #endregion
            rowIndex = ;
            foreach (DataRow row in dtSource.Rows)
            {
                )
                    sheet = workbook.CreateSheet();
                #region 填充数据

                var dataRow = sheet.CreateRow(rowIndex);
                foreach (DataColumn column in dtSource.Columns)
                {
                    var newCell = dataRow.CreateCell(column.Ordinal);
                    var cellValue = row[column].ToString();
                    switch (column.DataType.ToString())
                    {
                        //字符串类型
                        case "System.String":
                            double result;
                            if (double.TryParse(cellValue, out result))
                            {
                                newCell.SetCellValue(result);
                                break;
                            }
                            newCell.SetCellValue(cellValue);
                            break;
                        //DateTime类型
                        case "System.DateTime":
                            DateTime tmpdt;
                            if (DateTime.TryParse(cellValue, out tmpdt))
                            {
                                newCell.SetCellValue(tmpdt);
                                newCell.CellStyle = dateStyle;
                                break;
                            }
                            newCell.SetCellValue(cellValue);
                            break;
                        //布尔类型
                        case "System.Boolean":
                            bool boolV;
                            if (bool.TryParse(cellValue, out boolV))
                            {
                                newCell.SetCellValue(boolV);
                                break;
                            }
                            newCell.SetCellValue(cellValue);
                            break;
                        //整型
                        case "System.Int16":
                        case "System.Int32":
                        case "System.Int64":
                        case "System.Byte":
                            int intV;
                            if (int.TryParse(cellValue, out intV))
                            {
                                newCell.SetCellValue(intV);
                                break;
                            }
                            newCell.SetCellValue(cellValue);
                            break;
                        //浮点型
                        case "System.Decimal":
                        case "System.Double":
                            double doubV;
                            if (double.TryParse(cellValue, out doubV))
                            {
                                newCell.SetCellValue(doubV);
                                break;
                            }
                            newCell.SetCellValue(cellValue);
                            break;
                        //空值处理
                        case "System.DBNull":
                            newCell.SetCellValue("");
                            break;
                        default:
                            newCell.SetCellValue("");
                            break;

                    }
                }
                rowIndex++;

                #endregion

            }
            using (var ms = new MemoryStream())
            {
                workbook.Write(ms);
                ms.Flush();
                ms.Position = ;
                return ms;
            }
        }
        /// <summary>
        /// DataTable导出到Excel文件
        /// </summary>
        /// <param name="dtSource">源DataTable</param>
        /// <param name="headerText">表头</param>
        /// <param name="fileName">Excel文件保存位置(包含文件名)</param>
        public static void ExportDataTableToExcel(DataTable dtSource, string headerText,string fileName)
        {
            using (var ms = ExportDataTable(dtSource, headerText))
            {
                using (var fileStream = new FileStream(fileName, FileMode.Create, FileAccess.Write))
                {
                    var data = ms.ToArray();
                    fileStream.Write(data,,data.Length);
                    fileStream.Flush();
                }
            }
        }

测试从DataTable数据导出至Excel的表如下图所示(限于篇幅,图中只有一部分数据):

测试代码如下:

生成的文件如下图所示:

其次是读取Excel模板文件,代码关键部分有注释说明,具体代码如下所示:

/// <summary>
        /// 将sheet页导出至DataTable中
        /// </summary>
        /// <param name="sheet">需要导出的sheet</param>
        /// <param name="headerRowIndex">表头所在行号,-1表示没有列头</param>
        /// <returns>返回的DataTable</returns>
        public static DataTable ImportSheetToDataTable(HSSFSheet sheet, int headerRowIndex)
        {
            var dataTable = new DataTable();
            try
            {
                HSSFRow headerRow;
                int cellCount;
                )
                {
                    headerRow = (HSSFRow)sheet.GetRow();
                    cellCount = headerRow.LastCellNum;

                    for (int i = headerRow.FirstCellNum; i <= cellCount; i++)
                    {
                        var column = new DataColumn(i.ToString(CultureInfo.InvariantCulture));
                        dataTable.Columns.Add(column);
                    }
                }
                else
                {
                    headerRow = (HSSFRow)sheet.GetRow(headerRowIndex+);
                    cellCount = headerRow.LastCellNum;

                    for (int i = headerRow.FirstCellNum; i < cellCount; i++)
                    {
                        if (headerRow.GetCell(i) == null)
                        {
                            )
                            {
                                var column = new DataColumn("重复列名" + i);
                                dataTable.Columns.Add(column);
                            }
                            else
                            {
                                var column = new DataColumn(Convert.ToString(i));
                                dataTable.Columns.Add(column);
                            }

                        }
                        )
                        {
                            var column = new DataColumn("重复列名" + i);
                            dataTable.Columns.Add(column);
                        }
                        else
                        {
                            var column = new DataColumn(headerRow.GetCell(i).ToString());
                            dataTable.Columns.Add(column);
                        }
                    }
                }
                ); i <= sheet.LastRowNum; i++)
                {
                    try
                    {
                        HSSFRow row;
                        if (sheet.GetRow(i) == null)
                        {
                            row = sheet.CreateRow(i) as HSSFRow;
                        }
                        else
                        {
                            row = sheet.GetRow(i) as HSSFRow;
                        }

                        var dataRow = dataTable.NewRow();

                        if (row != null)
                            for (int j = row.FirstCellNum; j <= cellCount; j++)
                            {
                                try
                                {
                                    if (row.GetCell(j) == null) continue;
                                    switch (row.GetCell(j).CellType)
                                    {
                                        case CellType.STRING:
                                            var str = row.GetCell(j).StringCellValue;
                                            if (!string.IsNullOrEmpty(str))
                                            {
                                                dataRow[j] = str;
                                            }
                                            else
                                            {
                                                dataRow[j] = null;
                                            }
                                            break;
                                        case CellType.NUMERIC:
                                            if (DateUtil.IsCellDateFormatted(row.GetCell(j)))
                                            {
                                                dataRow[j] = DateTime.FromOADate(row.GetCell(j).NumericCellValue);
                                            }
                                            else
                                            {
                                                dataRow[j] = Convert.ToDouble(row.GetCell(j).NumericCellValue);
                                            }
                                            break;
                                        case CellType.BOOLEAN:
                                            dataRow[j] = Convert.ToString(row.GetCell(j).BooleanCellValue);
                                            break;
                                        case CellType.ERROR:
                                            dataRow[j] = ErrorEval.GetText(row.GetCell(j).ErrorCellValue);
                                            break;
                                        case CellType.FORMULA:
                                            switch (row.GetCell(j).CachedFormulaResultType)
                                            {
                                                case CellType.STRING:
                                                    var strFormula = row.GetCell(j).StringCellValue;
                                                    if (!string.IsNullOrEmpty(strFormula))
                                                    {
                                                        dataRow[j] = strFormula;
                                                    }
                                                    else
                                                    {
                                                        dataRow[j] = null;
                                                    }
                                                    break;
                                                case CellType.NUMERIC:
                                                    dataRow[j] = Convert.ToString(row.GetCell(j).NumericCellValue);
                                                    break;
                                                case CellType.BOOLEAN:
                                                    dataRow[j] = Convert.ToString(row.GetCell(j).BooleanCellValue);
                                                    break;
                                                case CellType.ERROR:
                                                    dataRow[j] = ErrorEval.GetText(row.GetCell(j).ErrorCellValue);
                                                    break;
                                                default:
                                                    dataRow[j] = "";
                                                    break;
                                            }
                                            break;
                                        default:
                                            dataRow[j] = "";
                                            break;
                                    }
                                }
                                catch (Exception)
                                {
                                    //这里添加异常异常日志记录
                                    return null;
                                }
                            }
                        dataTable.Rows.Add(dataRow);
                    }
                    catch (Exception)
                    {
                        //这里添加异常异常日志记录
                        return null;
                    }
                }
            }
            catch (Exception)
            {
                //这里添加异常异常日志记录
                return null;
            }
            return dataTable;
        }
        /// <summary>
        /// 将Excel指定sheet数据导出至DataTable中
        /// </summary>
        /// <param name="fileName"></param>
        /// <param name="sheetIndex"></param>
        /// <param name="headerRowIndex"></param>
        /// <returns>返回的DataTable</returns>
        public static DataTable ImportExcelToDataTable(string fileName, int sheetIndex, int headerRowIndex)
        {
            HSSFWorkbook workbook;
            using (var fileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read))
            {
                workbook = new HSSFWorkbook(fileStream);
            }
            HSSFSheet sheet = (HSSFSheet)workbook.GetSheetAt(sheetIndex);
            var dataTable = ImportSheetToDataTable(sheet, headerRowIndex);
            workbook = null;
            sheet = null;
            return dataTable;
        }

测试读取Excel模板文件使用上面生成的test.xls文件,测试代码如下所示:

通过加入的断点,debug可以看到读取得到的DataTable文件正常,如下图所示:

最后是修改Excel模板文件,修改Excel模板中一列的值,代码关键部分有注释说明,具体代码如下所示:

/// <summary>
        /// 更新Excel表格
        /// </summary>
        /// <param name="outputFile">需更新的excel表格路径</param>
        /// <param name="sheetname">sheet名</param>
        /// <param name="updateData">需更新的数据</param>
        /// <param name="coluid">需更新的列号</param>
        /// <param name="rowid">需更新的开始行号</param>
        public static void UpdateExcel(string outputFile, string sheetname, double[] updateData, int coluid, int rowid)
        {
            var readfile = new FileStream(outputFile, FileMode.Open, FileAccess.Read);

            var hssfworkbook = new HSSFWorkbook(readfile);
            var sheet1 = hssfworkbook.GetSheet(sheetname);
            ; i < updateData.Length; i++)
            {
                try
                {
                    if (sheet1.GetRow(i + rowid) == null)
                    {
                        sheet1.CreateRow(i + rowid);
                    }
                    if (sheet1.GetRow(i + rowid).GetCell(coluid) == null)
                    {
                        sheet1.GetRow(i + rowid).CreateCell(coluid);
                    }

                    sheet1.GetRow(i + rowid).GetCell(coluid).SetCellValue(updateData[i]);
                }
                catch (Exception ex)
                {
                    //这里添加异常异常日志记录
                    throw;
                }
            }
            try
            {
                readfile.Close();
                var writefile = new FileStream(outputFile, FileMode.Create, FileAccess.Write);
                hssfworkbook.Write(writefile);
                writefile.Close();
            }
            catch (Exception ex)
            {
                //这里添加异常异常日志记录
            }

        }

测试代码如下(使用上面生成的test.xls文件):

生成后的test.xls文件红色框中的部分为修改的部分,打开如下所示:

整个代码如下所示:

using System;
using System.Data;
using System.Globalization;
using System.IO;
using System.Text;
using NPOI.HPSF;
using NPOI.SS.Formula.Eval;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.SS.Util;
using System.Collections;

namespace DotNetCommon.Excel
{
    /// <summary>
    /// 类说明:Excel操作静态类(基于NPOI组件)
    /// 编码人:鞠小军
    /// 联系方式:binghuojxj@qq.com
    /// </summary>
    public static class ExcelHelper
    {
        /// <summary>
        /// 获取Excel文件sheet页总数
        /// </summary>
        /// <param name="outputFile">要读取Excel文件</param>
        /// <returns></returns>
        public static int GetSheetNumber(string outputFile)
        {
            ;
            try
            {
                var readFile = new FileStream(outputFile, FileMode.Open, FileAccess.Read);
                var workbook = new HSSFWorkbook(readFile);
                number = workbook.NumberOfSheets;
            }
            catch (Exception)
            {
                //这里添加异常异常日志记录
                ;
            }
            return number;
        }
        /// <summary>
        /// 获取Excel文件sheet名称集合
        /// </summary>
        /// <param name="outputFile">要读取Excel文件</param>
        /// <returns></returns>
        public static ArrayList GetSheetName(string outputFile)
        {
            var arrayList = new ArrayList();
            try
            {
                var readFile = new FileStream(outputFile, FileMode.Open, FileAccess.Read);
                var workbook = new HSSFWorkbook(readFile);
                ; i < workbook.NumberOfSheets; i++)
                {
                    arrayList.Add(workbook.GetSheetName(i));
                }

            }
            catch (Exception)
            {
                //这里添加异常异常日志记录
                return null;
            }
            return arrayList;
        }
        /// <summary>
        /// 从DataTable中将数据导出到Excel文件
        /// </summary>
        /// <param name="dtSource">提供导出数据的DataTable</param>
        /// <param name="headerText">表头文本</param>
        /// <returns></returns>
        public static MemoryStream ExportDataTable(DataTable dtSource, string headerText)
        {
            //创建工作表
            var workbook = new HSSFWorkbook();
            //创建sheet页
            var sheet = workbook.CreateSheet();
            #region 添加Excel文件属性信息

            var dsi = PropertySetFactory.CreateDocumentSummaryInformation();
            dsi.Company = "ZWKJ";
            workbook.DocumentSummaryInformation = dsi;

            var si = PropertySetFactory.CreateSummaryInformation();
            si.Author = "鞠小军";
            si.ApplicationName = "使用NPOI创建的Excel文件";
            si.CreateDateTime = DateTime.Now;
            workbook.SummaryInformation = si;

            #endregion

            //设置日期格式
            var dateStyle = workbook.CreateCellStyle();
            var format = workbook.CreateDataFormat();
            dateStyle.DataFormat = format.GetFormat("yyyy-mm-dd");
            //取得列宽
            var columnWidth = new int[dtSource.Columns.Count];
            //遍历DataTable的列
            foreach (DataColumn column in dtSource.Columns)
            {
                columnWidth[column.Ordinal] = Encoding.GetEncoding().GetBytes(column.ColumnName).Length;
            }
            //遍历所有的Row,若当前Row内容长度超出列名长度,则将此列的长度设为该Row内容长度
            ; i < dtSource.Rows.Count; i++)
            {
                ; j < dtSource.Columns.Count; j++)
                {
                    ).GetBytes(dtSource.Rows[i][j].ToString()).Length;
                    if (currentRowLength > columnWidth[j])
                        columnWidth[j] = currentRowLength;
                }
            }

            ;
            #region 表头及样式

            );
            headRow.HeightInPoints = ;
            headRow.CreateCell().SetCellValue(headerText);

            var headStyle = workbook.CreateCellStyle();
            headStyle.Alignment = HorizontalAlignment.CENTER;
            var font = workbook.CreateFont();
            font.Boldweight = ;
            font.FontHeightInPoints = ;
            headStyle.SetFont(font);
            headRow.GetCell().CellStyle = headStyle;
            sheet.AddMergedRegion(, , , dtSource.Columns.Count - ));
            #endregion
            #region 列头及样式

            );
            var columnStyle = workbook.CreateCellStyle();
            columnStyle.Alignment = HorizontalAlignment.CENTER;
            var columnFont = workbook.CreateFont();
            columnFont.Boldweight = ;
            columnFont.FontHeightInPoints = ;
            columnStyle.SetFont(columnFont);
            foreach (DataColumn column in dtSource.Columns)
            {
                //设置列头内容
                columnRow.CreateCell(column.Ordinal).SetCellValue(column.ColumnName);
                //设置列头样式
                columnRow.GetCell(column.Ordinal).CellStyle = columnStyle;
                //设置列宽
                sheet.SetColumnWidth(column.Ordinal, (columnWidth[column.Ordinal] + ) * );

            }
            #endregion
            rowIndex = ;
            foreach (DataRow row in dtSource.Rows)
            {
                )
                    sheet = workbook.CreateSheet();
                #region 填充数据

                var dataRow = sheet.CreateRow(rowIndex);
                foreach (DataColumn column in dtSource.Columns)
                {
                    var newCell = dataRow.CreateCell(column.Ordinal);
                    var cellValue = row[column].ToString();
                    switch (column.DataType.ToString())
                    {
                        //字符串类型
                        case "System.String":
                            double result;
                            if (double.TryParse(cellValue, out result))
                            {
                                newCell.SetCellValue(result);
                                break;
                            }
                            newCell.SetCellValue(cellValue);
                            break;
                        //DateTime类型
                        case "System.DateTime":
                            DateTime tmpdt;
                            if (DateTime.TryParse(cellValue, out tmpdt))
                            {
                                newCell.SetCellValue(tmpdt);
                                newCell.CellStyle = dateStyle;
                                break;
                            }
                            newCell.SetCellValue(cellValue);
                            break;
                        //布尔类型
                        case "System.Boolean":
                            bool boolV;
                            if (bool.TryParse(cellValue, out boolV))
                            {
                                newCell.SetCellValue(boolV);
                                break;
                            }
                            newCell.SetCellValue(cellValue);
                            break;
                        //整型
                        case "System.Int16":
                        case "System.Int32":
                        case "System.Int64":
                        case "System.Byte":
                            int intV;
                            if (int.TryParse(cellValue, out intV))
                            {
                                newCell.SetCellValue(intV);
                                break;
                            }
                            newCell.SetCellValue(cellValue);
                            break;
                        //浮点型
                        case "System.Decimal":
                        case "System.Double":
                            double doubV;
                            if (double.TryParse(cellValue, out doubV))
                            {
                                newCell.SetCellValue(doubV);
                                break;
                            }
                            newCell.SetCellValue(cellValue);
                            break;
                        //空值处理
                        case "System.DBNull":
                            newCell.SetCellValue("");
                            break;
                        default:
                            newCell.SetCellValue("");
                            break;

                    }
                }
                rowIndex++;

                #endregion

            }
            using (var ms = new MemoryStream())
            {
                workbook.Write(ms);
                ms.Flush();
                ms.Position = ;
                return ms;
            }
        }
        /// <summary>
        /// DataTable导出到Excel文件
        /// </summary>
        /// <param name="dtSource">源DataTable</param>
        /// <param name="headerText">表头</param>
        /// <param name="fileName">Excel文件保存位置(包含文件名)</param>
        public static void ExportDataTableToExcel(DataTable dtSource, string headerText,string fileName)
        {
            using (var ms = ExportDataTable(dtSource, headerText))
            {
                using (var fileStream = new FileStream(fileName, FileMode.Create, FileAccess.Write))
                {
                    var data = ms.ToArray();
                    fileStream.Write(data,,data.Length);
                    fileStream.Flush();
                }
            }
        }
        /// <summary>
        /// 将sheet页导出至DataTable中
        /// </summary>
        /// <param name="sheet">需要导出的sheet</param>
        /// <param name="headerRowIndex">表头所在行号,-1表示没有列头</param>
        /// <returns>返回的DataTable</returns>
        public static DataTable ImportSheetToDataTable(HSSFSheet sheet, int headerRowIndex)
        {
            var dataTable = new DataTable();
            try
            {
                HSSFRow headerRow;
                int cellCount;
                )
                {
                    headerRow = (HSSFRow)sheet.GetRow();
                    cellCount = headerRow.LastCellNum;

                    for (int i = headerRow.FirstCellNum; i <= cellCount; i++)
                    {
                        var column = new DataColumn(i.ToString(CultureInfo.InvariantCulture));
                        dataTable.Columns.Add(column);
                    }
                }
                else
                {
                    headerRow = (HSSFRow)sheet.GetRow(headerRowIndex+);
                    cellCount = headerRow.LastCellNum;

                    for (int i = headerRow.FirstCellNum; i < cellCount; i++)
                    {
                        if (headerRow.GetCell(i) == null)
                        {
                            )
                            {
                                var column = new DataColumn("重复列名" + i);
                                dataTable.Columns.Add(column);
                            }
                            else
                            {
                                var column = new DataColumn(Convert.ToString(i));
                                dataTable.Columns.Add(column);
                            }

                        }
                        )
                        {
                            var column = new DataColumn("重复列名" + i);
                            dataTable.Columns.Add(column);
                        }
                        else
                        {
                            var column = new DataColumn(headerRow.GetCell(i).ToString());
                            dataTable.Columns.Add(column);
                        }
                    }
                }
                ); i <= sheet.LastRowNum; i++)
                {
                    try
                    {
                        HSSFRow row;
                        if (sheet.GetRow(i) == null)
                        {
                            row = sheet.CreateRow(i) as HSSFRow;
                        }
                        else
                        {
                            row = sheet.GetRow(i) as HSSFRow;
                        }

                        var dataRow = dataTable.NewRow();

                        if (row != null)
                            for (int j = row.FirstCellNum; j <= cellCount; j++)
                            {
                                try
                                {
                                    if (row.GetCell(j) == null) continue;
                                    switch (row.GetCell(j).CellType)
                                    {
                                        case CellType.STRING:
                                            var str = row.GetCell(j).StringCellValue;
                                            if (!string.IsNullOrEmpty(str))
                                            {
                                                dataRow[j] = str;
                                            }
                                            else
                                            {
                                                dataRow[j] = null;
                                            }
                                            break;
                                        case CellType.NUMERIC:
                                            if (DateUtil.IsCellDateFormatted(row.GetCell(j)))
                                            {
                                                dataRow[j] = DateTime.FromOADate(row.GetCell(j).NumericCellValue);
                                            }
                                            else
                                            {
                                                dataRow[j] = Convert.ToDouble(row.GetCell(j).NumericCellValue);
                                            }
                                            break;
                                        case CellType.BOOLEAN:
                                            dataRow[j] = Convert.ToString(row.GetCell(j).BooleanCellValue);
                                            break;
                                        case CellType.ERROR:
                                            dataRow[j] = ErrorEval.GetText(row.GetCell(j).ErrorCellValue);
                                            break;
                                        case CellType.FORMULA:
                                            switch (row.GetCell(j).CachedFormulaResultType)
                                            {
                                                case CellType.STRING:
                                                    var strFormula = row.GetCell(j).StringCellValue;
                                                    if (!string.IsNullOrEmpty(strFormula))
                                                    {
                                                        dataRow[j] = strFormula;
                                                    }
                                                    else
                                                    {
                                                        dataRow[j] = null;
                                                    }
                                                    break;
                                                case CellType.NUMERIC:
                                                    dataRow[j] = Convert.ToString(row.GetCell(j).NumericCellValue);
                                                    break;
                                                case CellType.BOOLEAN:
                                                    dataRow[j] = Convert.ToString(row.GetCell(j).BooleanCellValue);
                                                    break;
                                                case CellType.ERROR:
                                                    dataRow[j] = ErrorEval.GetText(row.GetCell(j).ErrorCellValue);
                                                    break;
                                                default:
                                                    dataRow[j] = "";
                                                    break;
                                            }
                                            break;
                                        default:
                                            dataRow[j] = "";
                                            break;
                                    }
                                }
                                catch (Exception)
                                {
                                    //这里添加异常异常日志记录
                                    return null;
                                }
                            }
                        dataTable.Rows.Add(dataRow);
                    }
                    catch (Exception)
                    {
                        //这里添加异常异常日志记录
                        return null;
                    }
                }
            }
            catch (Exception)
            {
                //这里添加异常异常日志记录
                return null;
            }
            return dataTable;
        }
        /// <summary>
        /// 将Excel指定sheet数据导出至DataTable中
        /// </summary>
        /// <param name="fileName"></param>
        /// <param name="sheetIndex"></param>
        /// <param name="headerRowIndex"></param>
        /// <returns>返回的DataTable</returns>
        public static DataTable ImportExcelToDataTable(string fileName, int sheetIndex, int headerRowIndex)
        {
            HSSFWorkbook workbook;
            using (var fileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read))
            {
                workbook = new HSSFWorkbook(fileStream);
            }
            HSSFSheet sheet = (HSSFSheet)workbook.GetSheetAt(sheetIndex);
            var dataTable = ImportSheetToDataTable(sheet, headerRowIndex);
            workbook = null;
            sheet = null;
            return dataTable;
        }
        #region 更新excel中的数据
        /// <summary>
        /// 更新Excel表格
        /// </summary>
        /// <param name="outputFile">需更新的excel表格路径</param>
        /// <param name="sheetname">sheet名</param>
        /// <param name="updateData">需更新的数据</param>
        /// <param name="coluid">需更新的列号</param>
        /// <param name="rowid">需更新的开始行号</param>
        public static void UpdateExcel(string outputFile, string sheetname, string[] updateData, int coluid, int rowid)
        {
            FileStream readfile = new FileStream(outputFile, FileMode.Open, FileAccess.Read);

            HSSFWorkbook hssfworkbook = new HSSFWorkbook(readfile);
            ISheet sheet1 = hssfworkbook.GetSheet(sheetname);
            ; i < updateData.Length; i++)
            {
                try
                {
                    if (sheet1.GetRow(i + rowid) == null)
                    {
                        sheet1.CreateRow(i + rowid);
                    }
                    if (sheet1.GetRow(i + rowid).GetCell(coluid) == null)
                    {
                        sheet1.GetRow(i + rowid).CreateCell(coluid);
                    }

                    sheet1.GetRow(i + rowid).GetCell(coluid).SetCellValue(updateData[i]);
                }
                catch (Exception ex)
                {
                    // 这里添加异常异常日志记录
                    throw;
                }
            }
            try
            {
                readfile.Close();
                FileStream writefile = new FileStream(outputFile, FileMode.Create, FileAccess.Write);
                hssfworkbook.Write(writefile);
                writefile.Close();
            }
            catch (Exception ex)
            {
                // 这里添加异常异常日志记录
            }

        }

        /// <summary>
        /// 更新Excel表格
        /// </summary>
        /// <param name="outputFile">需更新的excel表格路径</param>
        /// <param name="sheetname">sheet名</param>
        /// <param name="updateData">需更新的数据</param>
        /// <param name="coluids">需更新的列号</param>
        /// <param name="rowid">需更新的开始行号</param>
        public static void UpdateExcel(string outputFile, string sheetname, string[][] updateData, int[] coluids, int rowid)
        {
            var readfile = new FileStream(outputFile, FileMode.Open, FileAccess.Read);

            var hssfworkbook = new HSSFWorkbook(readfile);
            readfile.Close();
            var sheet1 = hssfworkbook.GetSheet(sheetname);
            ; j < coluids.Length; j++)
            {
                ; i < updateData[j].Length; i++)
                {
                    try
                    {
                        if (sheet1.GetRow(i + rowid) == null)
                        {
                            sheet1.CreateRow(i + rowid);
                        }
                        if (sheet1.GetRow(i + rowid).GetCell(coluids[j]) == null)
                        {
                            sheet1.GetRow(i + rowid).CreateCell(coluids[j]);
                        }
                        sheet1.GetRow(i + rowid).GetCell(coluids[j]).SetCellValue(updateData[j][i]);
                    }
                    catch (Exception ex)
                    {
                        // 这里添加异常异常日志记录
                    }
                }
            }
            try
            {
                var writefile = new FileStream(outputFile, FileMode.Create);
                hssfworkbook.Write(writefile);
                writefile.Close();
            }
            catch (Exception ex)
            {
                //这里添加异常异常日志记录
            }
        }

        /// <summary>
        /// 更新Excel表格
        /// </summary>
        /// <param name="outputFile">需更新的excel表格路径</param>
        /// <param name="sheetname">sheet名</param>
        /// <param name="updateData">需更新的数据</param>
        /// <param name="coluid">需更新的列号</param>
        /// <param name="rowid">需更新的开始行号</param>
        public static void UpdateExcel(string outputFile, string sheetname, double[] updateData, int coluid, int rowid)
        {
            var readfile = new FileStream(outputFile, FileMode.Open, FileAccess.Read);

            var hssfworkbook = new HSSFWorkbook(readfile);
            var sheet1 = hssfworkbook.GetSheet(sheetname);
            ; i < updateData.Length; i++)
            {
                try
                {
                    if (sheet1.GetRow(i + rowid) == null)
                    {
                        sheet1.CreateRow(i + rowid);
                    }
                    if (sheet1.GetRow(i + rowid).GetCell(coluid) == null)
                    {
                        sheet1.GetRow(i + rowid).CreateCell(coluid);
                    }

                    sheet1.GetRow(i + rowid).GetCell(coluid).SetCellValue(updateData[i]);
                }
                catch (Exception ex)
                {
                    //这里添加异常异常日志记录
                    throw;
                }
            }
            try
            {
                readfile.Close();
                var writefile = new FileStream(outputFile, FileMode.Create, FileAccess.Write);
                hssfworkbook.Write(writefile);
                writefile.Close();
            }
            catch (Exception ex)
            {
                //这里添加异常异常日志记录
            }

        }

        /// <summary>
        /// 更新Excel表格
        /// </summary>
        /// <param name="outputFile">需更新的excel表格路径</param>
        /// <param name="sheetname">sheet名</param>
        /// <param name="updateData">需更新的数据</param>
        /// <param name="coluids">需更新的列号</param>
        /// <param name="rowid">需更新的开始行号</param>
        public static void UpdateExcel(string outputFile, string sheetname, double[][] updateData, int[] coluids, int rowid)
        {
            var readfile = new FileStream(outputFile, FileMode.Open, FileAccess.Read);

            var hssfworkbook = new HSSFWorkbook(readfile);
            readfile.Close();
            var sheet1 = hssfworkbook.GetSheet(sheetname);
            ; j < coluids.Length; j++)
            {
                ; i < updateData[j].Length; i++)
                {
                    try
                    {
                        if (sheet1.GetRow(i + rowid) == null)
                        {
                            sheet1.CreateRow(i + rowid);
                        }
                        if (sheet1.GetRow(i + rowid).GetCell(coluids[j]) == null)
                        {
                            sheet1.GetRow(i + rowid).CreateCell(coluids[j]);
                        }
                        sheet1.GetRow(i + rowid).GetCell(coluids[j]).SetCellValue(updateData[j][i]);
                    }
                    catch (Exception ex)
                    {
                        //这里添加异常异常日志记录
                    }
                }
            }
            try
            {
                var writefile = new FileStream(outputFile, FileMode.Create);
                hssfworkbook.Write(writefile);
                writefile.Close();
            }
            catch (Exception)
            {
                //这里添加异常异常日志记录
            }
        }

        #endregion

    }
}
测试使用的文件打包,如下所示:测试用打包文件下载

【个人使用.Net类库】(3)Excel文件操作类(基于NPOI)的更多相关文章

  1. 对Aspose.Cells Excel文件操作的扩展

    工作中对Excel操作的需求很是常见,今天其他项目组的同事在进行Excel数据导入时,使用Aspose.Cells Excel 遇到了些问题. 刚好闲来不忙,回想自己用过的Excel文件操作,有NPO ...

  2. C# 文件操作类大全

      C# 文件操作类大全 时间:2015-01-31 16:04:20      阅读:1724      评论:0      收藏:0      [点我收藏+] 标签: 1.创建文件夹 //usin ...

  3. [C#] 常用工具类——文件操作类

    /// <para> FilesUpload:工具方法:ASP.NET上传文件的方法</para> /// <para> FileExists:返回文件是否存在&l ...

  4. 文件操作类CFile

    CFile file; CString str1= L"写入文件成功!"; wchar_t *str2; if (!file.Open(L"Hello.txt" ...

  5. asp.net文件操作类

    /** 文件操作类 **/ #region 引用命名空间 using System; using System.Collections.Generic; using System.Text; usin ...

  6. android 文件操作类简易总结

    android 文件操作类(参考链接) http://www.cnblogs.com/menlsh/archive/2013/04/02/2997084.html package com.androi ...

  7. Ini文件操作类

    /// <summary> /// Ini文件操作类 /// </summary> public class Ini { // 声明INI文件的写操作函数 WritePriva ...

  8. java csv 文件 操作类

    一个CSV文件操作类,功能比较齐全: package tool; import java.io.BufferedReader; import java.io.BufferedWriter; impor ...

  9. Qt5:Qt文件操作类 QFile

    在QT中,操作文件一般不使用C++提供的文件操作类 , 因为操作文件的时候,要用到C++提供的 string 类,而在QT中使用的是Qt自己实现的一个string类 QString .在Qt中使用C+ ...

随机推荐

  1. AJAX-----13HTML5中新增的API---FormData

    FormData 表单数据对象,这是在HTML5中新增的一个API,他能以表单对象做参数,自动的将表单的数据打包,当ajax发送数据是,发送FormData内的表单数据给后端即可 <!DOCTY ...

  2. Frag(匹配跟踪)

    ‘碎片’(Frag)跟踪是目标跟踪里的一种通过‘部分‘匹配识别的方法,其目标模板是通过图像多个碎片和块来描述.块是任意的,不基于目标模型的(与传统的基于’部分‘的方法不一样,比如人体的四肢与躯干的跟踪 ...

  3. SQL2005中的事务与锁定(八)- 转载

    ------------------------------------------------------------------------ -- Author : happyflystone - ...

  4. 滑动的Button

    在介绍SwitchButton之前,先来看一下系统Button是如何实现的.源码如下: @RemoteView public class Button extends TextView { publi ...

  5. Python之logging模块

    一.引言 之前在写一些小程序的时候想把日志内容打到文件中,所以就自己写了一个logger.py的程序,如下: #!/usr/bin/python # -*- coding=utf-8 -*- impo ...

  6. xcode 创建项目 勾选 git 出现警告

    1. 解决方法: 在mac机上找到终端工具  >> 这里先介绍下使用Command-line. 1,下载Git installer,地址:http://git-scm.com/downlo ...

  7. [课程设计]Scrum 2.1 多鱼点餐系统开发进度(下单列表布局)

    [课程设计]Scrum 2.1 多鱼点餐系统开发进度(下单列表布局) 1.团队名称:重案组 2.团队目标:长期经营,积累客户充分准备,伺机而行 3.团队口号:矢志不渝,追求完美 4.团队选题:餐厅到店 ...

  8. aliyun的yum源(国内速度极快)

    公网(家里宽带下载速度达到1-3.5M): http://mirrors.aliyun.com/repo/Centos-6.repo 内网(购买的阿里云主机可以访问): http://mirrors. ...

  9. 学DIV+CSS技术,如何入门?(2)

    http://www.zhangbin.in/a/jishuziliao/CSSjishu/2014/0730/13267_2.html

  10. Maven学习(四)-- 生命周期和插件

    标签(空格分隔): 学习笔记 Maven生命周期是抽象的,不做任何实际的工作,在Maven的设计中,实际的任务都交由插件来完成. 每个构件步骤都可以绑定一个或者多个插件行为,而且Maven为大多数构建 ...