文档章节

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

深圳大道
 深圳大道
发布于 2016/12/29 15:38
字数 1315
阅读 10
收藏 0
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


本文转载自:http://blog.csdn.net/smartsmile2012/article/details/8111119

深圳大道
粉丝 3
博文 877
码字总数 0
作品 0
深圳
架构师
私信 提问
纯.NET实现的Office文件读写组件 - NPOI

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

Neuzilla
2009/01/22
0
9
NPOI 2.1.1 发布,.NET 版的 POI

NPOI 2.1.1 发布,此版本为 beta 版本,现已提供下载: NPOI 2.1.1 binary NPOI 2.1 examples 更新后的NPOI支持office2007及以上了!!! 更多改进内容请看发行说明。 NPOI 是 POI 项目的 .N...

笨蛋EGG
2014/12/09
18.2K
8
Office文档处理 Apache POI 3.6 发布

Apache POI是一个开源的Java读写Excel、WORD等微软OLE2组件文档的项目。目前POI已经有了Ruby版本。 该版本值得注意的改进内容包括: 包含一个轻量级的 ooxml-schemas-1.0.jar 改名为 poi-oo...

红薯
2009/12/16
1K
1
Office文档的Java处理包--POI

Apache POI是一个开源的Java读写Excel、WORD等微软OLE2组件文档的项目。目前POI已经有了Ruby版本。 结构: HSSF - 提供读写Microsoft Excel XLS格式档案的功能。 XSSF - 提供读写Microsoft...

匿名
2008/09/18
105K
8
Apache POI 3.14-beta1 发布

Apache POI 3.14-beta1 发布,主要更新如下: 更多介绍请看:发行说明。 Apache POI 是一个开源的Java读写Excel、WORD等微软OLE2组件文档的项目。目前POI已经有了Ruby版本。 结构: HSSF - ...

oschina
2015/12/25
1K
4

没有更多内容

加载失败,请刷新页面

加载更多

nproc systemd on CentOS 7

Increasing nproc for processes launched by systemd on CentOS 7 Ask Question I have successfully increased the nofile and nproc value for the local users, but I couldn't find a p......

MtrS
21分钟前
1
0
了解微信小程序下拉刷新功能

小程序提供了这个事件。 onPullDownRefresh() 监听用户下拉刷新事件。 如果要开启下拉刷新功能,要先到json配置: "enablePullDownRefresh":true 配置后下拉有反应了但是没有加载效果,在onP...

oixan__
46分钟前
2
0
springmvc java对象转json,上传下载(未完)拦截器Interceptor以及源码解析(未完待续)

package com.atguigu.my.controller;import java.util.Collection;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Contr......

architect刘源源
今天
29
0
[日更-2019.5.24、25、26] Android系统中的Binder通信机制分析(一)--servicemanager

声明 其实对于Android系统Binder通信的机制早就有分析的想法,记得去年6、7月份Mr.Deng离职期间约定一起对其进行研究的,但因为我个人问题没能实施这个计划,留下些许遗憾... 最近,刚好在做...

Captain_小馬佩德罗
昨天
24
0
聊聊dubbo的DataStore

序 本文主要研究一下dubbo的DataStore DataStore dubbo-2.7.2/dubbo-common/src/main/java/org/apache/dubbo/common/store/DataStore.java @SPI("simple")public interface DataStore { ......

go4it
昨天
3
0

没有更多内容

加载失败,请刷新页面

加载更多