• 使用NPOI 导入导出Excel的类


    1.   整个Excel表格叫做工作表:WorkBook(工作薄),包含的叫页(工作表):Sheet;行:Row;单元格Cell

    2.  NPOIPOI项目的.NET版本,是由@Tony Qu(http://tonyqus.cnblogs.com/)等大侠基于POI开发的,可以从http://npoi.codeplex.com/下载到它的最新版本。它不使用Office COM组件(Microsoft.Office.Interop.XXX.dll),不需要安装MicrosoftOffice,支持对Office 97-2003的文件格式,功能比较强大。更详细的说明请看官方网站。
    NPOI能够分析Excel文件的格式,能够进行常用Excel操作,不依赖于Excel,节省资源,没有安全性、性能的问题,在ASP.net中用最合适。只能处理xls格式文件、不能处理xlsx这样的新版本Excel文件格式。处理office 2007 以上版本用OpenXML。)

    它有以下一些特性:

    1. 支持对标准的Excel读写

    2. 支持对流(Stream)的读写 (而Jet OLEDB和Office COM都只能针对文件)

    3. 支持大部分Office COM组件的常用功能

    4. 性能优异 (相对于前面的方法)

    5. 使用简单,易上手

    使用NPOI

    本文使用的版本是1.2.4,此版本的程序集缩减至2个:NPOI.dllIonic.Zip.dll,直接引用到项目中即可。

    对于我们开发者使用的对象主要位于NPOI.HSSF.UserModel空间下,主要有HSSFWorkbookHSSFSheetHSSFRowHSSFCell,对应的接口为位于NPOI.SS.UserModel空间下的IWorkbookISheetIRowICell,分别对应Excel文件、工作表、行、列。

    创建一个Workbook对象,添加一个工作表,在工作表中添加一行一列:

    using NPOI.HSSF.UserModel;
    using NPOI.SS.UserModel;
     
    public class NPOIWrite
    {
        void CreateSheet()
        {
            IWorkbook workbook = new HSSFWorkbook();//创建Workbook对象
            ISheet sheet = workbook.CreateSheet("Sheet1");//创建工作表
            IRow row = sheet.CreateRow(0);//在工作表中添加一行
            ICell cell = row.CreateCell(0);//在行中添加一列
            cell.SetCellValue("test");//设置列的内容
        }
    }

    相应的读取代码:

    using System.IO;
    using NPOI.HSSF.UserModel;
    using NPOI.SS.UserModel;
     
    public class NPOIRead
    {
        void GetSheet(Stream stream)
        {
            IWorkbook workbook = new HSSFWorkbook(stream);//从流内容创建Workbook对象
            ISheet sheet = workbook.GetSheetAt(0);//获取第一个工作表
            IRow row = sheet.GetRow(0);//获取工作表第一行
            ICell cell = row.GetCell(0);//获取行的第一列
            string value = cell.ToString();//获取列的值
        }
    }

    使用NPOI导入导出类

    using System;
    using System.Collections.Generic;
    using System.Data;
    using System.IO;
    using System.Text;
    using System.Web;
    using NPOI;
    using NPOI.HPSF;
    using NPOI.HSSF;
    using NPOI.HSSF.Record;//NPOI.HSSF.Record.Formula.Eval改为了NPOI.SS.Formula.Eval;
    using NPOI.SS.Formula.Eval;//同上
    using NPOI.HSSF.UserModel;
    using NPOI.HSSF.Util;
    using NPOI.POIFS;
    using NPOI.SS.UserModel;
    using NPOI.Util;
    using NPOI.SS;
    using NPOI.DDF;
    using NPOI.SS.Util;
    using System.Collections;
    using System.Text.RegularExpressions;
    
    namespace System
    {
        public class ExcelHelper
        {
            //private static WriteLog wl = new WriteLog();
    
            #region DataTable转换成Excel文档流,并输出到客户端
            /// <summary>
            /// 自动设置Excel列宽
            /// </summary>
            /// <param name="sheet">Excel表</param>
            private static void AutoSizeColumns(ISheet sheet)
            {
                if (sheet.PhysicalNumberOfRows > 0)
                {
                    IRow headerRow = sheet.GetRow(0);
    
                    for (int i = 0, l = headerRow.LastCellNum; i < l; i++)
                    {
                        sheet.AutoSizeColumn(i);
                    }
                }
            }
            /// <summary>
            /// DataTable转换成Excel文档流,并输出到客户端
            /// </summary>
            /// <param name="table"></param>
            /// <param name="response"></param>
            /// <param name="fileName">输出的文件名</param>
            public static void RenderToExcel(DataTable table, HttpContext context, string fileName, string sheetName)
            {
                using (MemoryStream ms = RenderToExcel(table, sheetName))
                {
                    RenderToBrowser(ms, context, fileName);
                }
            }
            /// <summary>
            /// DataTable转换成Excel文档流
            /// </summary>
            /// <param name="table"></param>
            /// <returns></returns>
            public static MemoryStream RenderToExcel(DataTable table, string sheetName)
            {
                MemoryStream ms = new MemoryStream();
    
                using (table)
                {
                    HSSFWorkbook workbook = new HSSFWorkbook();
                    HSSFSheet sheet = workbook.CreateSheet(sheetName) as HSSFSheet;
                    IRow headerRow = sheet.CreateRow(0);
    
                    // handling header.
                    foreach (DataColumn column in table.Columns)
                        headerRow.CreateCell(column.Ordinal).SetCellValue(column.Caption);//If Caption not set, returns the ColumnName value
    
                    // handling value.
                    int rowIndex = 1;
    
                    foreach (DataRow row in table.Rows)
                    {
                        IRow dataRow = sheet.CreateRow(rowIndex);
    
                        foreach (DataColumn column in table.Columns)
                        {
                            dataRow.CreateCell(column.Ordinal).SetCellValue(row[column].ToString());
                        }
    
                        rowIndex++;
                    }
                    AutoSizeColumns(sheet);
    
                    workbook.Write(ms);
                    ms.Flush();
                    ms.Position = 0;
                }
                return ms;
            }
            /// <summary>
            /// 输出文件到浏览器
            /// </summary>
            /// <param name="ms">Excel文档流</param>
            /// <param name="context">HTTP上下文</param>
            /// <param name="fileName">文件名</param>
            private static void RenderToBrowser(MemoryStream ms, HttpContext context, string fileName)
            {
                if (context.Request.Browser.Browser == "IE")
                    fileName = HttpUtility.UrlEncode(fileName);
                context.Response.AddHeader("Content-Disposition", "attachment;fileName=" + fileName);
                context.Response.BinaryWrite(ms.ToArray());
            }
            #endregion
    
            #region DataTable导出到Excel文件
            /// <summary>
            /// DataTable导出到Excel的MemoryStream
            /// </summary>
            /// <param name="dtSource">源DataTable</param>
            /// <param name="strHeaderText">表头文本</param>
            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;
    
                    //sheet;
                    //workbook.Dispose();
    
                    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)
            {
                DataTable dt = new DataTable();
                HSSFWorkbook hssfworkbook;
                using (FileStream file = new FileStream(strFileName, FileMode.Open, FileAccess.Read))
                {
                    hssfworkbook = new HSSFWorkbook(file);
                }
                HSSFSheet sheet = hssfworkbook.GetSheetAt(0) as HSSFSheet;
                dt = ImportDt(sheet, 0, true);
                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 <= sheet.LastRowNum; 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 (str != null && str.Length > 0)
                                                {
                                                    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 (strFORMULA != null && strFORMULA.Length > 0)
                                                        {
                                                            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)
                                {
                                    //wl.WriteLogs(exception.ToString());
                                }
                            }
                            table.Rows.Add(dataRow);
                        }
                        catch (Exception exception)
                        {
                            //wl.WriteLogs(exception.ToString());
                        }
                    }
                }
                catch (Exception exception)
                {
                    //wl.WriteLogs(exception.ToString());
                }
                return table;
            }
            #endregion
    
            #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);
                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)
                    {
                        // 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, 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)
                    {
                        //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;
            }
        }
    }

    使用例子导出:

            protected void btDownload_Click(object sender, EventArgs e)
            {
                PatientNursingMonitor dal = new PatientNursingMonitor();
                DataTable dt = dal.GetTable("");
                if (dt != null && dt.Rows.Count > 0)
                {
                    DataTable dtExcel = new DataTable();                
                    dtExcel.Columns.Add(new DataColumn("监控时间", typeof(DateTime)));                
                    dtExcel.Columns.Add(new DataColumn("评分", typeof(string)));                
                    foreach (DataRow dr in dt.Rows)
                    {
                        DataRow row = dtExcel.NewRow();                   
                        row["监控时间"] = dr["MonitorDate"].ToString();                    
                        row["评分"] = dr["Score"].ToString();                    
                        dtExcel.Rows.Add(row);
                    }
    
                    HttpContext context = HttpContext.Current;
                    string excelName = DateTime.Now.ToString("yyyyMMddHHmm") + "xxx.xls";
    
                    //ExcelHelper.ExportDTtoExcel(dtDDJKJL, null, "c:\" + excelName);
                    ExcelHelper.RenderToExcel(dtExcel, context, excelName, "sheet1");
                }
                else
                {
                    lbMsg.Items.Add("暂无记录");
                }
            }

    使用例子导入

            protected void btInsertYP_Click(object sender, EventArgs e)
            {
                string path = Server.MapPath("/files/YPM.xls");
                DataTable dt = ExcelHelper.ImportExceltoDt(path, 0, -1);
                Drug dal = new Drug();
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    DrugInfo info = new DrugInfo();
                    info.DrugName = dt.Rows[i][2].ToString();//药品名称
                    info.DrugType = dt.Rows[i][5].ToString();//药品类别
                    info.Unit = dt.Rows[i][4].ToString();//单位
                    if (dal.Insert(info) > 0)
                    {
                    }
                }
            }

    版权声明:本文为博主原创文章,未经博主允许不得转载。

  • 相关阅读:
    html之marquee详解
    委托delegate
    sql server 循环
    数据库可疑
    WP8数据存储--独立存储文件
    WP8数据存储--独立存储设置
    jQuery Mobile 自定义导航条图标
    JQuery Mobile 图片布局
    自定义jQuery Mobile工具栏按钮
    css透明度的设置 (兼容所有浏览器)
  • 原文地址:https://www.cnblogs.com/ful1021/p/4804511.html
Copyright © 2020-2023  润新知