利用NPOI开源的读写Excel、WORD等微软OLE2组件读写execl,控制样式或单元格

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
//add
using System.Data;
using System.IO;
using NPOI;
using NPOI.HSSF.UserModel;

public partial class ExeclOperation : System.Web.UI.Page
{
    #region 页面加载
    protected void Page_Load(object sender, EventArgs e)
    {
        DataTable dt = ReadExcelToDataTable("~/xls/demo001.xls", 0, 0);
        ViewState["dtview"] = dt;
        GridView1.DataSource = dt;
        GridView1.DataBind();
    }
    #endregion 

    #region DS直接生成Execl
    protected void btnExport_Click(object sender, EventArgs e)
    {
        DataSet ds = new DataSet();
        DataTable dt = ViewState["dtview"] as DataTable;
        ds.Tables.Add(dt);
        bool success = ExportExcelByDataSet(ds, "~/xls/", "demo.xls", "这是测试数据");
        if (success)
        {
            ScriptManager.RegisterClientScriptBlock(Page, typeof(Page), "alert1", "alert(‘生成execl文件成功‘)", true);
        }
        else
        {
            ScriptManager.RegisterClientScriptBlock(Page, typeof(Page), "alert2", "alert(‘生成execl文件失败‘)", true);
        }
    }
    #endregion 

    #region GridView自动列适应,不换行
    protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow || e.Row.RowType == DataControlRowType.Header)
        {
            TableCellCollection cells1 = e.Row.Cells;
            for (int i = 0; i < cells1.Count; i++)
            {
                cells1[i].Wrap = false;
            }
        }
    }
    #endregion 

    #region DataSet与Execl互转
    /// <summary>
    /// 传入ds直接生成excel文件
    /// </summary>
    /// <param name="ds">DataSet</param>
    /// <param name="strPath">文件路径</param>
    /// <param name="strFileName">文件名</param>
    /// <param name="ReportHeader">execl表头</param>
    /// <returns></returns>
    public static bool ExportExcelByDataSet(DataSet ds, string strPath, string strFileName, string ReportHeader = "")
    {
        //NPOI
        HSSFWorkbook hssfworkbook2 = new HSSFWorkbook();
        HSSFSheet sheet = (HSSFSheet)hssfworkbook2.CreateSheet("sheet1");
        //定义字体 font   设置字体类型和大小
        HSSFFont font = (HSSFFont)hssfworkbook2.CreateFont();
        font.FontName = "宋体";
        font.FontHeightInPoints = 11;

        //定义单元格格式;单元格格式style1 为font的格式
        HSSFCellStyle style1 = (HSSFCellStyle)hssfworkbook2.CreateCellStyle();
        style1.SetFont(font);
        style1.Alignment = NPOI.SS.UserModel.HorizontalAlignment.LEFT;

        HSSFCellStyle style2 = (HSSFCellStyle)hssfworkbook2.CreateCellStyle();
        style2.SetFont(font);
        style2.Alignment = NPOI.SS.UserModel.HorizontalAlignment.CENTER;
        style2.BorderBottom = NPOI.SS.UserModel.BorderStyle.THIN;
        style2.BorderLeft = NPOI.SS.UserModel.BorderStyle.THIN;
        style2.BorderRight = NPOI.SS.UserModel.BorderStyle.THIN;
        style2.BorderTop = NPOI.SS.UserModel.BorderStyle.THIN;
        //style2.WrapText = true;

        //设置大标题行
        int RowCount = 0;
        int arrFlag = 0;
        string TileName1 = "";
        string TileName2 = "";

        string s = ReportHeader;
        string[] sArray = s.Split(‘|‘);
        if (ReportHeader != "")
        {
            foreach (string i in sArray)
            {
                string str1 = i.ToString();
                string[] subArray = str1.Split(‘@‘);
                foreach (string k in subArray)
                {
                    Console.WriteLine(k.ToString());
                    if (arrFlag == 0)
                    {
                        TileName1 = k.ToString();
                    }
                    else
                    {
                        TileName2 = k.ToString();
                    }
                    arrFlag = arrFlag + 1;
                }
                HSSFRow row0 = (HSSFRow)sheet.CreateRow(RowCount); //创建报表表头标题  8列
                row0.CreateCell(0).SetCellValue(TileName1);
                row0.CreateCell(1).SetCellValue(TileName2);
                RowCount = RowCount + 1;
                arrFlag = 0;
            }
        }
        //设置全局列宽和行高
        sheet.DefaultColumnWidth = 14;//全局列宽
        sheet.DefaultRowHeightInPoints = 15;//全局行高
        //设置标题行数据
        int a = 0;
        string mColumnName = "";

        HSSFRow row1 = (HSSFRow)sheet.CreateRow(RowCount); //创建报表表头标题  8列
        for (int k = 0; k < ds.Tables[0].Columns.Count; k++)
        {

            mColumnName = ds.Tables[0].Columns[k].ColumnName.ToString();
            row1.CreateCell(a).SetCellValue(mColumnName);
            row1.Cells[a].CellStyle = style2;
            a++;

        }
        //填写ds数据进excel
        for (int i = 0; i < ds.Tables[0].Rows.Count; i++)//写6行数据
        {
            HSSFRow row2 = (HSSFRow)sheet.CreateRow(i + RowCount + 1);
            int b = 0;
            for (int j = 0; j < ds.Tables[0].Columns.Count; j++)
            {
                string DgvValue = "";
                DgvValue = ds.Tables[0].Rows[i][j].ToString(); ;
                row2.CreateCell(b).SetCellValue(DgvValue);
                b++;
            }
        }
        //获取用户选择路径
        string ReportPath = HttpContext.Current.Server.MapPath(strPath + strFileName);

        //创建excel
        System.IO.FileStream file3 = new FileStream(ReportPath, FileMode.Create);
        hssfworkbook2.Write(file3);
        file3.Close();
        return true;
    }

    /// <summary>
    /// 用NPOI直接读取excel返回DataTable
    /// </summary>
    /// <param name="ExcelFileStream">文件流</param>
    /// <param name="SheetIndex">Sheet序号</param>
    /// <param name="StartRowIndex">开始行号</param>
    /// <returns></returns>
    public static DataTable ReadExcelToDataTable(Stream ExcelFileStream, int SheetIndex, int StartRowIndex)
    {
        HSSFWorkbook workbook = new HSSFWorkbook(ExcelFileStream);
        HSSFSheet sheet = (HSSFSheet)workbook.GetSheetAt(SheetIndex);

        DataTable table = new DataTable();
        HSSFRow headerRow = (HSSFRow)sheet.GetRow(StartRowIndex);
        int cellCount = headerRow.LastCellNum;

        for (int i = headerRow.FirstCellNum; i < cellCount; i++)
        {
            DataColumn column = new DataColumn(headerRow.GetCell(i).StringCellValue);
            table.Columns.Add(column);
        }
        int rowCount = sheet.LastRowNum;
        for (int i = (StartRowIndex + 1); i <= sheet.LastRowNum; i++)
        {
            HSSFRow row = (HSSFRow)sheet.GetRow(i);
            DataRow dataRow = table.NewRow();
            for (int j = row.FirstCellNum; j < cellCount; j++)
            {
                if (row.GetCell(j) != null)
                    dataRow[j] = row.GetCell(j).ToString();
            }
            table.Rows.Add(dataRow);
        }
        ExcelFileStream.Close();
        workbook = null;
        sheet = null;
        return table;
    }

    /// <summary>
    /// 用NPOI直接读取excel返回DataTable
    /// </summary>
    /// <param name="FilePath">文件路径</param>
    /// <param name="SheetIndex">Sheet序号</param>
    /// <param name="StartRowIndex">开始行号</param>
    /// <returns></returns>
    public static DataTable ReadExcelToDataTable(string FilePath, int SheetIndex, int StartRowIndex)
    {
        DataSet ds = new DataSet();
        FileStream fs = File.Open(HttpContext.Current.Server.MapPath(FilePath), FileMode.Open);
        DataTable dt = ReadExcelToDataTable(fs, SheetIndex, StartRowIndex);
        return dt;
    }
    #endregion
}
        #region DataSet与Execl互转
        /// <summary>
        /// 传入ds直接生成excel文件
        /// </summary>
        /// <param name="ds">DataSet</param>
        /// <param name="strPath">文件路径</param>
        /// <param name="ReportHeader">execl表头</param>
        /// <returns></returns>
        public static bool ExportExcelByDataSet(DataSet ds, string strPath, string ReportHeader = "")
        {
            //NPOI
            HSSFWorkbook hssfworkbook2 = new HSSFWorkbook();
            #region 循环开始
            for (int p = 0; p < ds.Tables.Count; p++)
            {
                int t = p + 1;
                HSSFSheet sheet = (HSSFSheet)hssfworkbook2.CreateSheet("page" + t);
                //定义字体 font   设置字体类型和大小
                HSSFFont font = (HSSFFont)hssfworkbook2.CreateFont();
                font.FontName = "宋体";
                font.FontHeightInPoints = 11;

                //定义单元格格式;单元格格式style1 为font的格式
                HSSFCellStyle style1 = (HSSFCellStyle)hssfworkbook2.CreateCellStyle();
                style1.SetFont(font);
                style1.Alignment = NPOI.SS.UserModel.HorizontalAlignment.LEFT;

                HSSFCellStyle style2 = (HSSFCellStyle)hssfworkbook2.CreateCellStyle();
                style2.SetFont(font);
                style2.Alignment = NPOI.SS.UserModel.HorizontalAlignment.CENTER;
                style2.BorderBottom = NPOI.SS.UserModel.BorderStyle.THIN;
                style2.BorderLeft = NPOI.SS.UserModel.BorderStyle.THIN;
                style2.BorderRight = NPOI.SS.UserModel.BorderStyle.THIN;
                style2.BorderTop = NPOI.SS.UserModel.BorderStyle.THIN;
                //style2.WrapText = true;    

                //设置大标题行
                int RowCount = 0;
                int arrFlag = 0;
                string TileName1 = "";
                string TileName2 = "";

                string s = ReportHeader;
                string[] sArray = s.Split(‘|‘);
                if (ReportHeader != "")
                {
                    foreach (string i in sArray)
                    {
                        string str1 = i.ToString();
                        string[] subArray = str1.Split(‘@‘);
                        foreach (string k in subArray)
                        {
                            Console.WriteLine(k.ToString());
                            if (arrFlag == 0)
                            {
                                TileName1 = k.ToString();
                            }
                            else
                            {
                                TileName2 = k.ToString();
                            }
                            arrFlag = arrFlag + 1;
                        }
                        HSSFRow row0 = (HSSFRow)sheet.CreateRow(RowCount); //创建报表表头标题  8列
                        row0.CreateCell(0).SetCellValue(TileName1);
                        row0.CreateCell(1).SetCellValue(TileName2);
                        RowCount = RowCount + 1;
                        arrFlag = 0;
                    }
                }
                //设置全局列宽和行高
                sheet.DefaultColumnWidth = 14;//全局列宽
                sheet.DefaultRowHeightInPoints = 15;//全局行高
                //设置标题行数据
                int a = 0;
                string mColumnName = "";

                HSSFRow row1 = (HSSFRow)sheet.CreateRow(RowCount); //创建报表表头标题  8列
                for (int k = 0; k < ds.Tables[p].Columns.Count; k++)
                {

                    mColumnName = ds.Tables[p].Columns[k].ColumnName.ToString();
                    row1.CreateCell(a).SetCellValue(mColumnName);
                    row1.Cells[a].CellStyle = style2;
                    a++;

                }
                //填写ds数据进excel
                for (int i = 0; i < ds.Tables[p].Rows.Count; i++)//写6行数据
                {
                    HSSFRow row2 = (HSSFRow)sheet.CreateRow(i + RowCount + 1);
                    int b = 0;
                    for (int j = 0; j < ds.Tables[p].Columns.Count; j++)
                    {
                        string DgvValue = "";
                        DgvValue = ds.Tables[p].Rows[i][j].ToString(); ;
                        row2.CreateCell(b).SetCellValue(DgvValue);
                        b++;
                    }
                }
            }
            #endregion

            //获取用户选择路径
            string ReportPath = (strPath);

            //创建excel
            System.IO.FileStream file3 = new FileStream(ReportPath, FileMode.Create);
            hssfworkbook2.Write(file3);
            file3.Close();
            return true;
        }

        /// <summary>
        /// 用NPOI直接读取excel返回DataSet
        /// </summary>
        /// <param name="ExcelFileStream">FileStream fs = File.Open(dlg.FileName, FileMode.Open);</param>
        /// <param name="SheetCount">sheet数量</param>
        /// <returns></returns>
        public static DataSet ReadExcelToDataSet(Stream ExcelFileStream,int SheetCount)
        {
            HSSFWorkbook workbook = new HSSFWorkbook(ExcelFileStream);
            DataSet ds = new DataSet();

            for (int k = 0; k < SheetCount; k++)
            {
                HSSFSheet sheet = (HSSFSheet)workbook.GetSheetAt(k);
                DataTable table = new DataTable("table" + k);
                HSSFRow headerRow = (HSSFRow)sheet.GetRow(0);
                int cellCount = headerRow.LastCellNum;

                for (int i = headerRow.FirstCellNum; i < cellCount; i++)
                {
                    string columnName = headerRow.GetCell(i).StringCellValue;
                    DataColumn column = new DataColumn(columnName);
                    if (!table.Columns.Contains(columnName))
                    {
                        table.Columns.Add(column);
                    }
                }
                int rowCount = sheet.LastRowNum;
                for (int i = (0 + 1); i <= sheet.LastRowNum; i++)
                {
                    HSSFRow row = (HSSFRow)sheet.GetRow(i);
                    DataRow dataRow = table.NewRow();
                    for (int j = row.FirstCellNum; j < cellCount; j++)
                    {
                        if (row.GetCell(j) != null)
                            dataRow[j] = row.GetCell(j);
                    }
                    table.Rows.Add(dataRow);
                }
                sheet = null;
                ds.Tables.Add(table);
            }
            workbook = null;
            ExcelFileStream.Close();

            return ds;
        }
        #endregion
时间: 2024-08-04 12:45:27

利用NPOI开源的读写Excel、WORD等微软OLE2组件读写execl,控制样式或单元格的相关文章

读写Excel、WORD等微软OLE2组件文档的项目

NPOI 是?POI?项目的 .NET 版本.POI是一个开源的Java读写Excel.WORD等微软OLE2组件文档的项目. 使用 NPOI 你就可以在没有安装 Office 或者相应环境的机器上对 WORD/EXCEL 文档进行读写. ? Apache POI是一个开源的Java读写Excel.WORD等微软OLE2组件文档的项目.目前POI已经有了Ruby版本. 结构: HSSF - 提供读写Microsoft Excel XLS格式档案的功能. XSSF - 提供读写Microsoft

POI生成EXCEL文件(字体、样式、单元格合并、计算公式)

创建一个封装类: 1 package com.jason.excel; 2 3 import java.io.FileNotFoundException; 4 import java.io.FileOutputStream; 5 import java.io.IOException; 6 7 import org.apache.poi.hssf.usermodel.HSSFCell; 8 import org.apache.poi.hssf.usermodel.HSSFCellStyle; 9

Excel设置下拉菜单并隐藏下拉菜单来源单元格内容

一.问题来源 做实验室的进展统计表,老师让加上开始时间和完成时间,时间格式:周几_上午(下午.晚上). 这样就可以了做下拉菜单,方便填写,而且格式统一,方便查看. 二.解决办法 2.1 下来菜单 红框是数据的来源区域,要设置成一行或者一列. 2.2 隐藏数据来源

POI是一个开源的读写Excel、WORD

NPOI 是?POI?项目的 .NET 版本.POI是一个开源的Java读写Excel.WORD等微软OLE2组件文档的项目. 使用 NPOI 你就可以在没有安装 Office 或者相应环境的机器上对 WORD/EXCEL 文档进行读写.

在Asp.Net MVC中使用NPOI插件实现对Excel的操作(导入,导出,合并单元格,设置样式,输入公式)

前言 NPOI 是 POI 项目的.NET版本,它不使用 Office COM 组件,不需要安装 Microsoft Office,目前支持 Office 2003 和 2007 版本. 1.整个Excel表格叫做工作表:WorkBook(工作薄),包含的叫页(工作表):Sheet:行:Row:单元格Cell. 2.NPOI是POI的C#版本,NPOI的行和列的index都是从0开始 3.POI读取Excel有两种格式一个是HSSF,另一个是XSSF. HSSF和XSSF的区别如下: HSSF

利用openpyxl模块来操作Excel

python 读写 excel 有好多选择,但是,方便操作的库不多,在我尝试了几个库之后,我觉得两个比较方便的库分别是 xlrd/xlwt.openpyxl. 之所以推荐两个库是因为这两个库分别操作的是不同版本的 excel,xlrd操作的是 xls/xlxs 格式的 excel,而 openpyxl 只支持 xlxs 格式的excel,openpyxl使用起来会更方便一些,所以如果你只操作 xlxs 文件的话,那么可以优先选择 openpyxl,如果要兼容 xls 的话,那就用 xlrd/xl

C#读写Excel(转)

网上找了很多方法,都没有突出重点,着急着用,快速总结一下,把重点部分突出. 读:ws.get_Range("A1", Type.Missing); 写:ws.Cells[1, 1] = "修改的内容"; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Li

[从产品角度学excel 04]-单元格的“衣服”

忘记发这里了..补发一下 这是<从产品角度学EXCEL>系列——单元格篇. 前言请看: 0 为什么要关注EXCEL的本质 1 excel是怎样运作的 2 EXCEL里的树形结构 3 单元格的秘密(文本/数字篇) 或者你可以去微信公众号@尾巴说数 获得连载目录. 本文仅由尾巴本人发布于特定网站.不接受任何无授权转载,如需转载,请先联系我,非常感谢. 抱歉之前因为有各种事情,一个多月没更新了,从今天开始恢复更新. 在前一章节里,我们通过对excel xml代码的阅读,发现在excel单元格里,文本

【转】NPOI 单元格级别应用

NPOI 单元格级别应用A HSSFWorkbook hssfworkbook = new HSSFWorkbook();//初始化一个新的HSSFWorkbook实例 //#region 1.创建一个空的Excel                ////*************************************创建一个空的Excel******************************************                ////HSSFSheet sh