• C#处理Excel的帮助类


    目录

     


     

    前言

    最近需要对Excel进行加密解密操作,本身是一个简单的事情,通过 OleDbConnection可以很容易进行操作Excel,或者也可以用第三方dll如NPOI进行操作。

     

    OleDb

    用OleDb方法几乎和SqlConnection一模一样,基本上把前缀Sql改成OleDb即可,不过有几个小细节需要注意。
    1. 我们可以把一个Excel当成一个数据源
    2. 每个sheet可以看成一张表
    3. 需要注意的是你在Excel看到的sheet名称后面需要加上$才是真正的sheet名字。

     

    具体操作

    我在此简单封装了下,取名为OleDbHelper,代码如下:

    using System;
    using System.Collections.Generic;
    using System.Data;
    using System.Data.OleDb;
    namespace ExcelDataEncipher
    {
        class OleDbHelper
        {
            private readonly string _connstr;
            //当前Sheet集合
            public IEnumerable<string> SheetNames { get; set; }
            //通过在外部传入数据源的名称来连接
            public OleDbHelper(string name)
            {
                _connstr = string.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties='Excel 8.0;ReadOnly=False;HDR=Yes;'", name);
                //这个连接串可以连接2003的,高版本Excel的连接串可能有所变化,由于我需要进行加密解密操作需要修改excel,所以ReadOnly设置为false 
                //同时HDR设置为Yes代表第一行是标题,不做为数据使用 
                this.GetSheetName();//获取所有Sheet名称
            }
            private void GetSheetName()
            {
                using (OleDbConnection conn = new OleDbConnection(_connstr))
                {
                    conn.Open();
                    using (DataTable dtSheetName = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] {null, null, null, "Table"}))
                    {
                        //包含excel中表名的字符串数组  
                        if (dtSheetName != null)
                        {
                            List<string> strTableNames = new List<string>();
                            for (int k = 0; k < dtSheetName.Rows.Count; k++)
                            {
                                strTableNames.Add(dtSheetName.Rows[k]["TABLE_NAME"].ToString());
                            }//获取Sheet名称
                            SheetNames = strTableNames;
                        }
                    }
                }
            }
            public int ExecuteNonQuery(string oleDb, 
                params OleDbParameter[] parameters)
            {
                using (OleDbConnection conn = new OleDbConnection(_connstr))
                {
                    conn.Open();
                    using (OleDbCommand cmd = conn.CreateCommand())
                    {
                        cmd.CommandText = oleDb;
                        cmd.Parameters.AddRange(parameters);
                        return cmd.ExecuteNonQuery();
                    }
                }
            }
            public object ExecuteScalar(string oleDb,
                params OleDbParameter[] parameters)
            {
                using (OleDbConnection conn = new OleDbConnection(_connstr))
                {
                    conn.Open();
                    using (OleDbCommand cmd = conn.CreateCommand())
                    {
                        cmd.CommandText = oleDb;
                        cmd.Parameters.AddRange(parameters);
                        return cmd.ExecuteScalar();
                    }
                }
            }
            public DataTable ExecuteDataTable(string oleDb,
                params OleDbParameter[] parameters)
            {
                using (OleDbConnection conn = new OleDbConnection(_connstr))
                {
                    conn.Open();
                    using (OleDbCommand cmd = conn.CreateCommand())
                    {
                        cmd.CommandText = oleDb;
                        cmd.Parameters.AddRange(parameters);
                        DataSet dataset = new DataSet();
                        OleDbDataAdapter adapter = new OleDbDataAdapter(cmd);
                        adapter.Fill(dataset);
                        return dataset.Tables[0];
                    }
                }
            }
            public static object FromDbValue(object value)
            {
                if (value == DBNull.Value)
                {
                    return null;
                }
                else
                {
                    return value;
                }
            }
            public static object ToDbValue(object value)
            {
                if (value == null)
                {
                    return DBNull.Value;
                }
                else
                {
                    return value;
                }
            }
        }
    }

    可以发现操作和对数据库操作一模一样

    我通过OpenFileDialog选择需要操作的文件

    foreach (var filename in openFile.FileNames)
    {
        string name = filename;
        _oleDbHelper = new OleDbHelper(name); //获取表
        string sheetName = _oleDbHelper.SheetNames.SingleOrDefault(s => s.Contains("Detail"));//查看名称是否包含Detail的sheet
        DataTable table = null;
        try
        {
            table = _oleDbHelper.ExecuteDataTable(string.Format("select * from [{0}]", sheetName));//将其转换为datatable
        }
        catch (Exception msg)
        {
            throw new Exception(msg.Message);
        }
        if (table.Rows.Count < 0)
        {
            MessageBox.Show("未找到任何记录");
            return;
        }
        for (int i = 0; i < table.Rows.Count; i++)
        {
            ...//处理数据
            try
            {
                ...//处理数据
                _oleDbHelper.ExecuteNonQuery(
                    string.Format(
                        "update [{0}] set [AccountNumber] = '{1}',[AccountName] = '{2}',[Price] = '{3}' where [Id] = '{4}'",
                        sheetName, table.Rows[i]["AccountNumber"], table.Rows[i]["AccountName"], table.Rows[i]["Price"],
                        table.Rows[i]["Id"]));
                //更新excel
            }
            catch (Exception msg)
            {
                throw new Exception(msg.Message);
            }
        }
    }

    本来通过参数化的形式进行更新,但是一直报错,不知道什么情况
    通过OleDb修改excel速度非常的慢,我的excel表 5行28列需要修改其中3列的数据需要1秒多,不知道是不是因为更新一个表格他会刷新整张excel还是为什么

     

    NPOI

    因为速度实在太慢,我不得不寻找其他的解决方法
    NPOI是一个开源的读写Excel、Word等项目,他的优点是不需要在机子上安装office也可以进行操作,而且读写速度还是非常快的。

     

    具体操作

    这里我在网上下载了别人的封装好的一个帮助类,略做了修改来适配我的项目:

    /*******************************************************************
     * 版权所有: 
     * 类 名 称:ExcelHelper
     * 作    者:zk
     * 电子邮箱: 
     * 创建日期:2012/2/25 10:17:21 
     * 修改描述:从excel导入datatable时,可以导入日期类型。
     *           但对excel中的日期类型有一定要求,要求至少是yyyy/mm/dd类型日期; *           
     * 修改描述:将datatable导入excel中,对类型为字符串的数字进行处理,
     *           导出数字为double类型;
     * 
     * 
     * *******************************************************************/
    using System;
    using System.Collections;
    using System.Collections.Generic;
    using System.Data;
    using System.IO;
    using System.Text;
    using System.Text.RegularExpressions;
    using NPOI.HSSF.UserModel;
    using NPOI.SS.Formula.Eval;
    using NPOI.SS.UserModel;
    using NPOI.SS.Util;
    namespace ExcelDataEncipher
    {
        public static class ExcelHelper
        {
            //private static WriteLog wl = new WriteLog();a
            #region 从datatable中将数据导出到excel
            /// <summary>
            /// DataTable导出到Excel的MemoryStream
            /// </summary>
            /// <param name="dtSource">源DataTable</param>
            /// <param name="strHeaderText">表头文本</param>
            public static MemoryStream ExportDT(DataTable dtSource, string strHeaderText)
            {
                HSSFWorkbook workbook = new HSSFWorkbook();
                HSSFSheet sheet = workbook.CreateSheet() as HSSFSheet;
                #region 右击文件 属性信息
                //{
                //    DocumentSummaryInformation dsi = PropertySetFactory.CreateDocumentSummaryInformation();
                //    dsi.Company = "http://www.yongfa365.com/";
                //    workbook.DocumentSummaryInformation = dsi;
                //    SummaryInformation si = PropertySetFactory.CreateSummaryInformation();
                //    si.Author = "柳永法"; //填加xls文件作者信息
                //    si.ApplicationName = "NPOI测试程序"; //填加xls文件创建程序信息
                //    si.LastAuthor = "柳永法2"; //填加xls文件最后保存者信息
                //    si.Comments = "说明信息"; //填加xls文件作者信息
                //    si.Title = "NPOI测试"; //填加xls文件标题信息
                //    si.Subject = "NPOI测试Demo"; //填加文件主题信息
                //    si.CreateDateTime = DateTime.Now;
                //    workbook.SummaryInformation = si;
                //}
                #endregion
                HSSFCellStyle dateStyle = workbook.CreateCellStyle() as HSSFCellStyle;
                HSSFDataFormat format = workbook.CreateDataFormat() as HSSFDataFormat;
                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() as HSSFSheet;
                        }
                        #region 表头及样式
                        {
                            HSSFRow headerRow = sheet.CreateRow(0) as HSSFRow;
                            headerRow.HeightInPoints = 25;
                            headerRow.CreateCell(0).SetCellValue(strHeaderText);
                            HSSFCellStyle headStyle = workbook.CreateCellStyle() as HSSFCellStyle;
                            headStyle.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Center;
                            HSSFFont font = workbook.CreateFont() as HSSFFont;
                            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));
                            //headerRow.Dispose();
                        }
                        #endregion
                        #region 列头及样式
                        {
                            HSSFRow headerRow = sheet.CreateRow(1) as HSSFRow;
                            HSSFCellStyle headStyle = workbook.CreateCellStyle() as HSSFCellStyle;
                            headStyle.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Center;
                            HSSFFont font = workbook.CreateFont() as HSSFFont;
                            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);
                            }
                            //headerRow.Dispose();
                        }
                        #endregion
                        rowIndex = 2;
                    }
                    #endregion
                    #region 填充内容
                    HSSFRow dataRow = sheet.CreateRow(rowIndex) as HSSFRow;
                    foreach (DataColumn column in dtSource.Columns)
                    {
                        HSSFCell newCell = dataRow.CreateCell(column.Ordinal) as HSSFCell;
                        string drValue = row[column].ToString();
                        switch (column.DataType.ToString())
                        {
                            case "System.String": //字符串类型
                                double result;
                                if (isNumeric(drValue, out result))
                                {
                                    double.TryParse(drValue, out result);
                                    newCell.SetCellValue(result);
                                    break;
                                }
                                else
                                {
                                    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;
                }
            }
            /// <summary>
            /// DataTable导出到Excel文件
            /// </summary>
            /// <param name="dtSource">源DataTable</param>
            /// <param name="strHeaderText">表头文本</param>
            /// <param name="strFileName">保存位置</param>
            public static void ExportDTtoExcel(DataTable dtSource, string strHeaderText, string strFileName)
            {
                using (MemoryStream ms = ExportDT(dtSource, strHeaderText))
                {
                    using (FileStream fs = new FileStream(strFileName, FileMode.Create, FileAccess.Write))
                    {
                        byte[] data = ms.ToArray();
                        fs.Write(data, 0, data.Length);
                        fs.Flush();
                    }
                }
            }
            #endregion
            #region 从excel中将数据导出到datatable
            /// <summary>读取excel
            /// 默认第一行为标头
            /// </summary>
            /// <param name="strFileName">excel文档路径</param>
            /// <returns></returns>
            public static DataTable ImportExceltoDt(string strFileName,string sheetName,bool includeTitle = true)
            {
                DataTable dt = new DataTable();
                HSSFWorkbook hssfworkbook;
                using (FileStream file = new FileStream(strFileName, FileMode.Open, FileAccess.Read))
                {
                    hssfworkbook = new HSSFWorkbook(file);
                }
                HSSFSheet sheet = hssfworkbook.GetSheet(sheetName) as HSSFSheet;
                if (sheet == null) return null;
                dt = ImportDt(sheet, 0, includeTitle);
                return dt;
            }
            /// <summary>
            /// 读取excel
            /// </summary>
            /// <param name="strFileName">excel文件路径</param>
            /// <param name="sheet">需要导出的sheet</param>
            /// <param name="HeaderRowIndex">列头所在行号,-1表示没有列头</param>
            /// <returns></returns>
            public static DataTable ImportExceltoDt(string strFileName, string SheetName, int HeaderRowIndex)
            {
                HSSFWorkbook workbook;
                using (FileStream file = new FileStream(strFileName, FileMode.Open, FileAccess.Read))
                {
                    workbook = new HSSFWorkbook(file);
                }
                HSSFSheet sheet = workbook.GetSheet(SheetName) as HSSFSheet;
                DataTable table = new DataTable();
                table = ImportDt(sheet, HeaderRowIndex, true);
                //ExcelFileStream.Close();
                workbook = null;
                sheet = null;
                return table;
            }
            /// <summary>
            /// 读取excel
            /// </summary>
            /// <param name="strFileName">excel文件路径</param>
            /// <param name="sheet">需要导出的sheet序号</param>
            /// <param name="HeaderRowIndex">列头所在行号,-1表示没有列头</param>
            /// <returns></returns>
            public static DataTable ImportExceltoDt(string strFileName, int SheetIndex, int HeaderRowIndex)
            {
                HSSFWorkbook workbook;
                using (FileStream file = new FileStream(strFileName, FileMode.Open, FileAccess.Read))
                {
                    workbook = new HSSFWorkbook(file);
                }
                HSSFSheet sheet = workbook.GetSheetAt(SheetIndex) as HSSFSheet;
                DataTable table = new DataTable();
                table = ImportDt(sheet, HeaderRowIndex, true);
                //ExcelFileStream.Close();
                workbook = null;
                sheet = null;
                return table;
            }
            /// <summary>
            /// 读取excel
            /// </summary>
            /// <param name="strFileName">excel文件路径</param>
            /// <param name="sheet">需要导出的sheet</param>
            /// <param name="HeaderRowIndex">列头所在行号,-1表示没有列头</param>
            /// <returns></returns>
            public static DataTable ImportExceltoDt(string strFileName, string SheetName, int HeaderRowIndex, bool needHeader)
            {
                HSSFWorkbook workbook;
                using (FileStream file = new FileStream(strFileName, FileMode.Open, FileAccess.Read))
                {
                    workbook = new HSSFWorkbook(file);
                }
                HSSFSheet sheet = workbook.GetSheet(SheetName) as HSSFSheet;
                DataTable table = new DataTable();
                table = ImportDt(sheet, HeaderRowIndex, needHeader);
                //ExcelFileStream.Close();
                workbook = null;
                sheet = null;
                return table;
            }
            /// <summary>
            /// 读取excel
            /// </summary>
            /// <param name="strFileName">excel文件路径</param>
            /// <param name="sheet">需要导出的sheet序号</param>
            /// <param name="HeaderRowIndex">列头所在行号,-1表示没有列头</param>
            /// <returns></returns>
            public static DataTable ImportExceltoDt(string strFileName, int SheetIndex, int HeaderRowIndex, bool needHeader)
            {
                HSSFWorkbook workbook;
                using (FileStream file = new FileStream(strFileName, FileMode.Open, FileAccess.Read))
                {
                    workbook = new HSSFWorkbook(file);
                }
                HSSFSheet sheet = workbook.GetSheetAt(SheetIndex) as HSSFSheet;
                DataTable table = new DataTable();
                table = ImportDt(sheet, HeaderRowIndex, needHeader);
                //ExcelFileStream.Close();
                workbook = null;
                sheet = null;
                return table;
            }
            /// <summary>
            /// 将制定sheet中的数据导出到datatable中
            /// </summary>
            /// <param name="sheet">需要导出的sheet</param>
            /// <param name="HeaderRowIndex">列头所在行号,-1表示没有列头</param>
            /// <returns></returns>
            static DataTable ImportDt(HSSFSheet sheet, int HeaderRowIndex, bool needHeader)
            {
                DataTable table = new DataTable();
                HSSFRow headerRow;
                int cellCount;
                try
                {
                    if (HeaderRowIndex < 0 || !needHeader)
                    {
                        headerRow = sheet.GetRow(0) as HSSFRow;
                        cellCount = headerRow.LastCellNum;
                        for (int i = headerRow.FirstCellNum; i < cellCount; i++)
                        {
                            DataColumn column = new DataColumn(Convert.ToString(i));
                            table.Columns.Add(column);
                        }
                    }
                    else
                    {
                        headerRow = sheet.GetRow(HeaderRowIndex) as HSSFRow;
                        cellCount = headerRow.LastCellNum;
                        for (int i = headerRow.FirstCellNum; i < cellCount; i++)
                        {
                            if (headerRow.GetCell(i) == null)
                            {
                                if (table.Columns.IndexOf(Convert.ToString(i)) > 0)
                                {
                                    DataColumn column = new DataColumn(Convert.ToString("重复列名" + i));
                                    table.Columns.Add(column);
                                }
                                else
                                {
                                    DataColumn column = new DataColumn(Convert.ToString(i));
                                    table.Columns.Add(column);
                                }
                            }
                            else if (table.Columns.IndexOf(headerRow.GetCell(i).ToString()) > 0)
                            {
                                DataColumn column = new DataColumn(Convert.ToString("重复列名" + i));
                                table.Columns.Add(column);
                            }
                            else
                            {
                                DataColumn column = new DataColumn(headerRow.GetCell(i).ToString());
                                table.Columns.Add(column);
                            }
                        }
                    }
                    int rowCount = sheet.LastRowNum;
                    for (int i = (HeaderRowIndex + 1); i <= rowCount; i++)
                    {
                        try
                        {
                            HSSFRow row;
                            if (sheet.GetRow(i) == null)
                            {
                                row = sheet.CreateRow(i) as HSSFRow;
                            }
                            else
                            {
                                row = sheet.GetRow(i) as HSSFRow;
                            }
                            DataRow dataRow = table.NewRow();
                            for (int j = row.FirstCellNum; j < cellCount; j++)
                            {
                                try
                                {
                                    if (row.GetCell(j) != null)
                                    {
                                        switch (row.GetCell(j).CellType)
                                        {
                                            case CellType.String:
                                                string str = row.GetCell(j).StringCellValue;
                                                if (!string.IsNullOrEmpty(str))
                                                {
                                                    dataRow[j] = str.ToString();
                                                }
                                                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:
                                                        string strFORMULA = row.GetCell(j).StringCellValue;
                                                        if (!string.IsNullOrEmpty(strFORMULA))
                                                        {
                                                            dataRow[j] = strFORMULA.ToString();
                                                        }
                                                        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 exception)
                                {
                                    throw  new Exception(exception.Message);
                                    //wl.WriteLogs(exception.ToString());
                                }
                            }
                            table.Rows.Add(dataRow);
                        }
                        catch (Exception exception)
                        {
                            throw new Exception(exception.Message);
                            //wl.WriteLogs(exception.ToString());
                        }
                    }
                }
                catch (Exception exception)
                {
                    throw new Exception(exception.Message);
                    //wl.WriteLogs(exception.ToString());
                }
                return table;
            }
            #endregion
            #region 更新excel中的数据
            /// <summary>
            /// 更新Excel表格
            /// </summary>
            /// <param name="outputFile">需更新的excel表格路径</param>
            /// <param name="sheetname">sheet名</param>
            /// <param name="data"></param>
            /// <param name="saveTitle"></param>
            public static bool UpdateExcel(string oldFile,string newFile, string sheetname,DataTable data,bool saveTitle = true)
            {
                try
                {
                    HSSFWorkbook hssfworkbook;
                    using (FileStream readfile = new FileStream(oldFile, FileMode.Open, FileAccess.Read))
                    {
                        hssfworkbook = new HSSFWorkbook(readfile);
                        ISheet sheet1 = hssfworkbook.GetSheet(sheetname);
                        int currentSheetRowIndex = 0;
                        if (saveTitle) currentSheetRowIndex = 1;
                        for (int i = 0; i < data.Rows.Count; i++, currentSheetRowIndex++)
                        {
                            for (int j = 0; j < data.Columns.Count; j++)
                            {
                                if (sheet1.GetRow(currentSheetRowIndex) == null)
                                    sheet1.CreateRow(currentSheetRowIndex);
                                if (sheet1.GetRow(currentSheetRowIndex).GetCell(j) == null)
                                    sheet1.GetRow(currentSheetRowIndex).CreateCell(j);
                                sheet1.GetRow(currentSheetRowIndex).GetCell(j).SetCellValue(data.Rows[i][j].ToString());
                            }
                        }
                    }
                    using (FileStream writefile = new FileStream(newFile, FileMode.Create, FileAccess.Write))
                    {
                        hssfworkbook.Write(writefile);
                    }
                }
                catch (IOException ioException)
                {
                    throw new IOException(ioException.Message);
                }
                catch (UnauthorizedAccessException unauthorizedAccessException)
                {
                    throw new UnauthorizedAccessException(unauthorizedAccessException.Message);
                }
                catch (Exception ex)
                {
                    throw new Exception(ex.Message);
                    // wl.WriteLogs(ex.ToString());
                }
                return true;
            }
            /// <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)
            {
                FileStream readfile = new FileStream(outputFile, FileMode.Open, FileAccess.Read);
                HSSFWorkbook hssfworkbook = new HSSFWorkbook(readfile);
                readfile.Close();
                ISheet sheet1 = hssfworkbook.GetSheet(sheetname);
                for (int j = 0; j < coluids.Length; j++)
                {
                    for (int i = 0; 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)
                        {
                            // wl.WriteLogs(ex.ToString());
                        }
                    }
                }
                try
                {
                    FileStream writefile = new FileStream(outputFile, FileMode.Create);
                    hssfworkbook.Write(writefile);
                    writefile.Close();
                }
                catch (Exception ex)
                {
                    //wl.WriteLogs(ex.ToString());
                }
            }
            /// <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)
            {
                FileStream readfile = new FileStream(outputFile, FileMode.Open, FileAccess.Read);
                HSSFWorkbook hssfworkbook = new HSSFWorkbook(readfile);
                ISheet sheet1 = hssfworkbook.GetSheet(sheetname);
                for (int i = 0; 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 new Exception(ex.Message);
                        //wl.WriteLogs(ex.ToString());
                        throw;
                    }
                }
                try
                {
                    readfile.Close();
                    FileStream writefile = new FileStream(outputFile, FileMode.Create, FileAccess.Write);
                    hssfworkbook.Write(writefile);
                    writefile.Close();
                }
                catch (Exception ex)
                {
                    //wl.WriteLogs(ex.ToString());
                }
            }
            /// <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)
            {
                FileStream readfile = new FileStream(outputFile, FileMode.Open, FileAccess.Read);
                HSSFWorkbook hssfworkbook = new HSSFWorkbook(readfile);
                readfile.Close();
                ISheet sheet1 = hssfworkbook.GetSheet(sheetname);
                for (int j = 0; j < coluids.Length; j++)
                {
                    for (int i = 0; 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)
                        {
                            //wl.WriteLogs(ex.ToString());
                        }
                    }
                }
                try
                {
                    FileStream writefile = new FileStream(outputFile, FileMode.Create);
                    hssfworkbook.Write(writefile);
                    writefile.Close();
                }
                catch (Exception ex)
                {
                    //wl.WriteLogs(ex.ToString());
                }
            }
            #endregion
            public static int GetSheetNumber(string outputFile)
            {
                int number = 0;
                try
                {
                    FileStream readfile = new FileStream(outputFile, FileMode.Open, FileAccess.Read);
                    HSSFWorkbook hssfworkbook = new HSSFWorkbook(readfile);
                    number = hssfworkbook.NumberOfSheets;
                }
                catch (Exception exception)
                {
                    //wl.WriteLogs(exception.ToString());
                }
                return number;
            }
            public static ArrayList GetSheetName(string outputFile)
            {
                ArrayList arrayList = new ArrayList();
                try
                {
                    FileStream readfile = new FileStream(outputFile, FileMode.Open, FileAccess.Read);
                    HSSFWorkbook hssfworkbook = new HSSFWorkbook(readfile);
                    for (int i = 0; i < hssfworkbook.NumberOfSheets; i++)
                    {
                        arrayList.Add(hssfworkbook.GetSheetName(i));
                    }
                }
                catch (Exception exception)
                {
                    //wl.WriteLogs(exception.ToString());
                }
                return arrayList;
            }
            public static bool isNumeric(String message, out double result)
            {
                Regex rex = new Regex(@"^[-]?d+[.]?d*$");
                result = -1;
                if (rex.IsMatch(message))
                {
                    result = double.Parse(message);
                    return true;
                }
                else return false;
            }
        }
    }

    调用方法:

    DataTable table = ExcelHelper.ImportExceltoDt(name,"Detail");//name是excel的路径txtSheetName是sheet名称
    success = ExcelHelper.UpdateExcel(name, newFileName, "Detail", table);//name是原excel名称,这里我需要把处理好的文件另存而不去修改源文件所以我加入了一个新的路径,table是需要保存的数据返回值为bool表示成功或失败

    通过测试NPOI速度为OLEDB的数十倍,

    出处:https://www.cnblogs.com/Jack-Blog/p/4692910.html

  • 相关阅读:
    什么是OOAD?什么是UML?
    Linux下Gvim 的基本操作-适合新手看
    关于mongodb ,redis,memcache之间见不乱理还乱的关系和作用
    phpcms常用标签
    请问如何更改dedecms“文件保存目录”的字符限制 ?
    如何通过刷百度指数来提高网站的权重
    HDU 1263(水果统计 **)
    HDU 1284(钱币兑换 背包/母函数)
    HDU 1028(数字拆分 分治)
    HDU 1036(平均速度 **)
  • 原文地址:https://www.cnblogs.com/mq0036/p/12748441.html
Copyright © 2020-2023  润新知