首页 > Windows开发 > 详细

C#利用NPOI逐行更新excel文件数据

时间:2017-07-21 20:40:59      阅读:999      评论:0      收藏:0      [点我收藏+]

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NPOI.SS.UserModel;
using NPOI.HSSF.UserModel;
using System.IO;

namespace www.xinduofen.cn
{
    class NpoiOperateExcel
    {

        /// <summary>
        /// 逐列创建excel文件
        /// </summary>
        /// <param name="data">为将要保存的数据,list《string》代表一列数据,有多少个就代表有多列数据(所有列上对齐)</param>
        /// <param name="save_address">代表excel表格将要保存的地址,包括"文件名.xls"</param>
        /// <param name="start_row">代表数据保存的起始行(1,2,3.......65536)最多支持65536行</param>
        /// <param name="sart_column">代表数据保存的起始列(1,2,3......256)最多支持256列</param>
        /// <param name="worksheet_name">代创建的工作表的名字(此函数只能只能填充一个工作表的内容)</param>
        /// <returns>返回 true 代表创建成功,否则为创建失败</returns>
        public static bool colCreate(List<List<string>> data, string save_address,
            int start_row, int sart_column, string worksheet_name)//创建一个excel表格
        {
            FileStream file = null;

            try
            {
                //如果传入参数合法
                if (data != null && !string.IsNullOrEmpty(save_address) && start_row > 0 && sart_column > 0)
                {
                    string sheetName = "Sheet1";
                    if (!string.IsNullOrEmpty(worksheet_name))
                    {
                        sheetName = worksheet_name;
                    }
                    IWorkbook workbook = new HSSFWorkbook();//创建Workbook对象
                    ISheet sheet = workbook.CreateSheet(sheetName);//创建工作表1
                    workbook.CreateSheet("Sheet2");//创建工作表2
                    workbook.CreateSheet("Sheet3");//创建工作表3

                    int columnIndex = sart_column - 1;//初始化起始列索引
                    foreach (List<string> list in data)
                    {
                        int rowIndex = start_row - 1;//初始化起始行索引
                        foreach (string str in list)
                        {
                            IRow row = sheet.GetRow(rowIndex);
                            if (row == null)
                            {
                                row = sheet.CreateRow(rowIndex);//在工作表中添加一行
                            }
                            ICell cell = row.CreateCell(columnIndex);//在行中添加一列
                            cell.SetCellValue(str);//设置列的内容

                            rowIndex++;//行索引向后移动
                        }

                        columnIndex++;//列索引向后移动
                    }
                    if (!save_address.EndsWith(".xls"))
                    {
                        save_address += ".xls";
                    }
                    file = new FileStream(save_address, FileMode.Create);
                    workbook.Write(file);

                    return true;//创建成功
                }
                else
                {
                    return false;//创建失败
                }
            }
            catch (Exception)
            {
                Console.WriteLine("NpoiOperateExcel.colCreate方法产生了异常!");
                return false;//创建失败
            }
            finally {
                if (file != null) { file.Close(); }
            }
        }

        /// <summary>
        /// 逐行更新excel文件
        /// </summary>
        /// <param name="data">为将要保存的数据,list《string》代表一行数据,有多少个就代表有多行数据(所有行左对齐)</param>
        /// <param name="save_address">代表将要更新的excel表格地址,包括"文件名.xls"</param>
        /// <param name="start_row">代表数据更新的起始行(1,2,3.......65536)最多支持65536行</param>
        /// <param name="sart_column">代表数据更新的起始列(1,2,3......256)最多支持256列</param>
        /// <param name="sheet_number">代表将要更新的sheet表的索引位置</param>
        /// <returns>返回 true 代表更新成功,否则为更新失败</returns>
        public static bool rowUpdate(List<List<string>> data, string save_address,
            int start_row, int sart_column, int sheet_number)//更新excel表格
        {
            FileStream writefile = null;

            try
            {
                //如果传入参数合法
                if (data != null && !string.IsNullOrEmpty(save_address) && start_row > 0 && sart_column > 0 && sheet_number > 0)
                {
                    FileStream readfile = null;
                    HSSFWorkbook hssfworkbook = null;
                    ISheet sheet = null;

                    try
                    {
                        readfile = new FileStream(save_address, FileMode.Open, FileAccess.Read);
                        hssfworkbook = new HSSFWorkbook(readfile);
                        sheet = hssfworkbook.GetSheetAt(sheet_number-1);
                    }
                    catch (Exception)
                    {
                        Console.WriteLine("NpoiOperateExcel.rowUpdate方法加载被更新文件时产生了异常!");
                    }
                    finally
                    {
                        if (readfile != null) { readfile.Close(); }
                    }

                    if (sheet != null)
                    {
                        int rowIndex = start_row - 1;//初始化起始行索引
                        foreach (List<string> list in data)
                        {
                            IRow row = sheet.GetRow(rowIndex);
                            if (row == null)
                            {
                                row = sheet.CreateRow(rowIndex);//在工作表中添加一行
                            }

                            int columnIndex = sart_column - 1;//初始化起始列索引
                            foreach (string str in list)
                            {
                                ICell cell = row.GetCell(columnIndex);
                                if (cell == null)
                                {
                                    cell = row.CreateCell(columnIndex);//在行中添加一列
                                }
                                cell.SetCellValue(str);//设置列的内容

                                columnIndex++;//列索引向后移动
                            }

                            rowIndex++;//行索引向后移动
                        }

                        writefile = new FileStream(save_address, FileMode.Create);
                        hssfworkbook.Write(writefile);

                        return true;//更新成功
                    }
                    else
                    {
                        return false;//更新失败
                    }
                }
                else
                {
                    return false;//更新失败
                }
            }
            catch (Exception)
            {
                Console.WriteLine("NpoiOperateExcel.rowUpdate方法产生了异常!");
                return false;//更新失败
            }
            finally {
                if (writefile!=null) { writefile.Close(); }
            }
        }

    }
}

内容所有权属于:北京继豪电子(公司专业研发体质测试仪

C#利用NPOI逐行更新excel文件数据

(2)
(2)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!