NPOI 2.0版本的使用

详细教程: http://blog.csdn.net/xxs77ch/article/details/50216033

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Configuration;
using System.Reflection;
using WSC.Common;
using System.IO;
using NPOI.SS.UserModel;
using NPOI.HSSF.UserModel;
using NPOI.SS.Util;


namespace WebApplication2
{
    public partial class _Default : System.Web.UI.Page
    {
        private string constr = ConfigurationManager.AppSettings["LocalConnectionString"];
        protected void Page_Load(object sender, EventArgs e)
        {

        }
        private DataTable getDT(string fid)
        {
            DataTable dt = new DataTable();
            if (string.IsNullOrEmpty(fid))
                Response.Write("");
            else
            {
                SQLHelper s = new SQLHelper(constr);
                string sql = @"";
                dt = s.Query(sql);
            }
            return dt;
        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            string fid = "001";
            DataTable datas = getDT(fid);
            if (datas.Rows.Count < 1)
                Response.Write("<script type=\"text/javascript\">alert('无相关信息,请先维护!')</script>");
            else
            {
                ExportExcel(datas, "nameExcel", "sheetName");
            }
        }

        /// <summary>
        /// DataTable导出Excel
        /// </summary>
        /// <param name="dt">datatable数据源</param>
        /// <param name="strFileName">文件名</param>
        /// <param name="strSheetName">工作簿名</param>
        public void ExportExcel(DataTable dt, string strFileName, string strSheetName)
        {
            IWorkbook book = new HSSFWorkbook();
            ISheet sheet = book.CreateSheet("sheetName");
            IRow dataRow = sheet.CreateRow(0);//创建一个对象,该对象表示着第一行(在createRow方法中,参数0能够得到体现)。
            ICell dataCell = dataRow.CreateCell(0);//创建一个对象,该对象表示着第一的第一列(在createCell方法中,参数0能够得到体现)。

            #region 头部
            dataCell.SetCellValue("头部信息");
            IFont font = book.CreateFont();//创建字体样式。这里只是创建了一个字体样式,
            ICellStyle style = book.CreateCellStyle();//创建一个样式

            font.FontName = "宋体";
            font.Boldweight = short.MaxValue;
            font.FontHeightInPoints = 28;

            font.Color = NPOI.HSSF.Util.HSSFColor.Grey50Percent.Index;
            style.SetFont(font);//将字体样式加到样式对象中去。
            dataCell.CellStyle = style;//将样式作用于dataCell对象,这个对象前面有提到过,指的是第一行第一列
            sheet.SetColumnWidth(0, 18 * 256);//设置第0行的列宽是18*256(256指的是字符)
            sheet.SetColumnWidth(1, 50 * 256);//设置第1行列宽是50*256
            sheet.SetColumnWidth(2, 28 * 256);
            sheet.SetColumnWidth(3, 18 * 256);

            ICellStyle style2 = book.CreateCellStyle();
            IFont font2 = book.CreateFont();
            font2.FontHeightInPoints = 20;
            font2.Color = NPOI.HSSF.Util.HSSFColor.Black.Index;

            style2.SetFont(font2);
            sheet.AddMergedRegion(new CellRangeAddress(0, 0, 1, 3));//合并单元格,前两位表示起始行,结束行。后两个表示起始列,结束列。
            dataCell = dataRow.CreateCell(1);
            style2.Alignment = HorizontalAlignment.Center;
            style2.VerticalAlignment = VerticalAlignment.Center;
            dataCell.SetCellValue("设置值");
            dataCell.CellStyle = style2;


            ICellStyle style3 = book.CreateCellStyle();
            dataRow = sheet.CreateRow(1);
            dataCell = dataRow.CreateCell(0);
            dataCell.SetCellValue("设置值");
            sheet.AddMergedRegion(new CellRangeAddress(1, 3, 0, 0));
            style3.Alignment = HorizontalAlignment.Center;
            style3.VerticalAlignment = VerticalAlignment.Center;
            dataCell.CellStyle = style3;
            ///设置机种名称
            sheet.AddMergedRegion(new CellRangeAddress(1, 3, 1, 1));
            dataCell = dataRow.CreateCell(1);
            dataCell.SetCellValue("设置值");
            ICellStyle styleType = book.CreateCellStyle();
            styleType.Alignment = HorizontalAlignment.Right;
            styleType.VerticalAlignment = VerticalAlignment.Center;
            dataCell.CellStyle = styleType;
            ICellStyle styleMachineType1 = book.CreateCellStyle();
            styleMachineType1.VerticalAlignment = VerticalAlignment.Center;
            styleMachineType1.Alignment = HorizontalAlignment.Right;
            sheet.AddMergedRegion(new CellRangeAddress(1,3,0,0));
            dataCell = dataRow.CreateCell(2);
            dataCell.SetCellValue("设置值");
            ICellStyle styleMachineType0 = book.CreateCellStyle();
            styleMachineType0.Alignment = HorizontalAlignment.Left;
            dataCell.CellStyle = styleMachineType0;

            dataRow = sheet.CreateRow(2);
            dataCell = dataRow.CreateCell(2);
            dataCell.SetCellValue("4H.15D36.A01");
            ICellStyle styleMachineType = book.CreateCellStyle();
            styleMachineType.Alignment = HorizontalAlignment.Left;
            dataCell.CellStyle = styleMachineType;

            //dataRow = sheet.CreateRow(2);
            dataCell = dataRow.CreateCell(3);
            dataCell.SetCellValue("设置值");

            dataRow = sheet.CreateRow(3);
            dataCell = dataRow.CreateCell(2);
            dataCell.SetCellValue("B156HAN");
            ICellStyle styleMachineType3 = book.CreateCellStyle();
            styleMachineType3.Alignment = HorizontalAlignment.Left;
            dataCell.CellStyle = styleMachineType3;
            ///设置机种名称
           

            #endregion

            #region 中间
            dataRow = sheet.CreateRow(4);
            ICellStyle style4 = book.CreateCellStyle();
            IFont font3 = book.CreateFont();
            font3.FontHeightInPoints = 18;
            style4.SetFont(font3);
            style4.Alignment = HorizontalAlignment.Center;
            style4.VerticalAlignment = VerticalAlignment.Center;

            string strColumns = "第一列,第二列,第三列";
            string[] strArry = strColumns.Split(',');
            for (int i = 0; i < strArry.Length; i++)
            {
                dataRow.CreateCell(i).SetCellValue(strArry[i]);
                dataRow.GetCell(i).CellStyle = style4;//设置样式
            }
            
                    ICellStyle bodyStyle = book.CreateCellStyle();
                    bodyStyle.Alignment = HorizontalAlignment.Center;
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                dataRow = sheet.CreateRow(i + 5);
                for (int j = 0; j < 3; j++)
                {
                    string ValueType = "";
                    string Value = "";
                    if (dt.Rows[i][j].ToString() != null)
                    {
                        ValueType = dt.Rows[i][j].GetType().ToString();
                        Value = dt.Rows[i][j].ToString();
                    }
                    switch (ValueType)
                    {
                        case "System.String"://字符串类型
                            if ((j == 2) && (Value != "OK"))
                            {
                                dataRow.CreateCell(j).SetCellValue("OK");
                                //dataRow.CreateCell(j + 1).CellStyle = bodyStyle;
                                //dataRow.CreateCell(j + 1).SetCellValue(Value);
                                dataCell = dataRow.CreateCell(j + 1);
                                dataCell.CellStyle = bodyStyle;
                                dataCell.SetCellValue(Value);
                                
                            }
                            else
                            {
                                dataRow.CreateCell(j).SetCellValue(Value);
                            }
                            break;
                        case "System.DateTime"://日期类型
                            System.DateTime dateV;
                            System.DateTime.TryParse(Value, out dateV);
                            dataRow.CreateCell(j).SetCellValue(dateV);
                            break;
                        case "System.Boolean"://布尔型
                            bool boolV = false;
                            bool.TryParse(Value, out boolV);
                            dataRow.CreateCell(j).SetCellValue(boolV);
                            break;
                        case "System.Int16"://整型
                        case "System.Int32":
                        case "System.Int64":
                        case "System.Byte":
                            int intV = 0;
                            int.TryParse(Value, out intV);
                            dataRow.CreateCell(j).SetCellValue(intV);
                            break;
                        case "System.Decimal"://浮点型
                        case "System.Double":
                            double doubV = 0;
                            double.TryParse(Value, out doubV);
                            dataRow.CreateCell(j).SetCellValue(doubV);
                            break;
                        case "System.DBNull"://空值处理
                            dataRow.CreateCell(j).SetCellValue("");
                            break;
                        default:
                            dataRow.CreateCell(j).SetCellValue("");
                            break;
                    }
                    if (j != 1)
                        dataRow.GetCell(j).CellStyle = bodyStyle;
                    //dataRow.GetCell(j).CellStyle = style;

                    //sheet.SetColumnWidth(j, (Value.Length + 10) * 256);//设置宽度
                }
            }
          
            #endregion

            #region 底部
            dataRow = sheet.CreateRow(5 + dt.Rows.Count);
            dataCell = dataRow.CreateCell(0);
            dataCell.SetCellValue("注:");
            ICellStyle styleFoot = book.CreateCellStyle();
            styleFoot.Alignment = HorizontalAlignment.Right;
            styleFoot.VerticalAlignment = VerticalAlignment.Top;
            IFont fontFoot = book.CreateFont();
            fontFoot.FontHeightInPoints = 20;
            styleFoot.SetFont(fontFoot);
            dataCell.CellStyle = styleFoot;
            sheet.AddMergedRegion(new CellRangeAddress(5 + dt.Rows.Count, 5 + dt.Rows.Count + 4, 0, 0));
            sheet.AddMergedRegion(new CellRangeAddress(6 + dt.Rows.Count, 6 + dt.Rows.Count, 1, 2));
            sheet.AddMergedRegion(new CellRangeAddress(7 + dt.Rows.Count, 7 + dt.Rows.Count, 1, 2));
            sheet.AddMergedRegion(new CellRangeAddress(8 + dt.Rows.Count, 8 + dt.Rows.Count, 1, 2));
            sheet.AddMergedRegion(new CellRangeAddress(5 + dt.Rows.Count, 5 + dt.Rows.Count, 1, 2));
            dataRow = sheet.CreateRow(6 + dt.Rows.Count);
            dataCell = dataRow.CreateCell(1);
            dataCell.SetCellValue("设置值");
            dataRow = sheet.CreateRow(7 + dt.Rows.Count);
            dataCell = dataRow.CreateCell(1);
            dataCell.SetCellValue("设置值");
            dataRow = sheet.CreateRow(8 + dt.Rows.Count);
            dataCell = dataRow.CreateCell(1);
            dataCell.SetCellValue("设置值");
            dataRow = sheet.CreateRow(9 + dt.Rows.Count);
            dataCell = dataRow.CreateCell(1);
            dataCell.SetCellValue("设置值");
            #endregion
     #region 插入图片
        byte[] bytes = System.IO.File.ReadAllBytes(@"F:\gch.jpg");//写成流      
        int pictureIdx = book.AddPicture(bytes, PictureType.PNG);//book是之前创建工作簿的名字
        HSSFPatriarch patriarch = (HSSFPatriarch)sheet.CreateDrawingPatriarch();//sheet是之前创建的表单
 HSSFClientAnchor anchor = new HSSFClientAnchor(0, 0, 1023, 0, 0, 0, 1, 3);//设置图片的尺寸及大小
        HSSFPicture pict = (HSSFPicture)patriarch.CreatePicture(anchor, pictureIdx);
        pict.Resize();
        #endregion
//关于HSSFClientAnchor(dx1,dy1,dx2,dy2,col1,row1,col2,row2)的参数,有必要在这里说明一下:
//dx1:起始单元格的x偏移量,如例子中的255表示直线起始位置距A1单元格左侧的距离;
//dy1:起始单元格的y偏移量,如例子中的125表示直线起始位置距A1单元格上侧的距离;
//dx2:终止单元格的x偏移量,如例子中的1023表示直线起始位置距C3单元格左侧的距离;
//dy2:终止单元格的y偏移量,如例子中的150表示直线起始位置距C3单元格上侧的距离;
//col1:起始单元格列序号,从0开始计算;
//row1:起始单元格行序号,从0开始计算,如例子中col1=0,row1=0就表示起始单元格为A1;
//col2:终止单元格列序号,从0开始计算;
//row2:终止单元格行序号,从0开始计算,如例子中col2=2,row2=2就表示起始单元格为C3;
一个有关NPOI的demo:http://blog.csdn.net/chinajiyong/article/details/9187485
            MemoryStream ms = new MemoryStream();
            book.Write(ms);
            Response.AddHeader("Content-Disposition", string.Format("attachment; filename={0}.xls", HttpUtility.UrlEncode(strFileName, System.Text.Encoding.UTF8)));
            Response.BinaryWrite(ms.ToArray());
            Response.End();
            book = null;
            ms.Close();
            ms.Dispose();
        }
    }
}

 

转载于:https://www.cnblogs.com/vichin/p/6209805.html

NPOI-2.2.0.0 的.net2.0和.net4.0版。(.net2.0版实测有效) (一)传统操作Excel遇到的问题: 1、如果是.NET,需要在服务器端装Office,且及时更新它,以防漏洞,还需要设定权限允许.NET访问COM+,如果在导出过程中出问题可能导致服务器宕机。 2、Excel会把只包含数字的列进行类型转换,本来是文本型的,Excel会将其转成数值型的,比如编号000123会变成123。 3、导出时,如果字段内容以“-”或“=”开头,Excel会把它当成公式进行,会报错。 4、Excel会根据Excel文件前8行分析数据类型,如果正好你前8行某一列只是数字,那它会认为该列为数值型,自动将该列转变成类似1.42702E+17格式,日期列变成包含日期和数字的。 (二)使用NPOI的优势 1、您可以完全免费使用该框架 2、包含了大部分EXCEL的特性(单元格样式、数据格式、公式等等) 3、专业的技术支持服务(24*7全天候) (非免费) 4、支持处理的文件格式包括xls, xlsx, docx. 5、采用面向接口的设计架构( 可以查看 NPOI.SS 的命名空间) 6、同时支持文件的导入和导出 7、基于.net 2.0 也支持xlsx 和 docx格式(当然也支持.net 4.0) 8、来自全世界大量成功且真实的测试Cases 9、大量的实例代码 11、你不需要在服务器上安装微软的Office,可以避免版权问题。 12、使用起来比Office PIA的API更加方便,更人性化。 13、你不用去花大力气维护NPOI,NPOI Team会不断更新、改善NPOI,绝对省成本。 14、不仅仅对与Excel可以进行操作,对于doc、ppt文件也可以做对应的操作 NPOI之所以强大,并不是因为它支持导出Excel,而是因为它支持导入Excel,并能“理解”OLE2文档结构,这也是其他一些Excel读写库比较弱的方面。通常,读入并理解结构远比导出来得复杂,因为导入你必须假设一切情况都是可能的,而生成你只要保证满足你自己需求就可以了,如果把导入需求和生成需求比做两个集合,那么生成需求通常都是导入需求的子集,这一规律不仅体现在Excel读写库中,也体现在pdf读写库中,目前市面上大部分的pdf库仅支持生成,不支持导入。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值