导出excel

/// <summary>
/// 增加二维码
/// </summary>
/// <param name="dt"></param>
/// <param name="isexcel"></param>
protected void AddPicture(DataTable dt, bool isexcel = true)
{ if (!Directory.Exists(imageBasePath))
{
Directory.CreateDirectory(imageBasePath);
}
if (!Directory.Exists(excelBasePath))
{
Directory.CreateDirectory(excelBasePath);
}
//创建工作薄
HSSFWorkbook workbook = new HSSFWorkbook();
//create sheet
HSSFSheet sheet = (HSSFSheet)workbook.CreateSheet("二维码打印");
string FileName ="二维码"+DateTime.Now.ToString("yyyyMMddhhmmss") + ".xls";
string strQrCodePath = "";
//填充列标题以及样式
int rowsNum = 0; //行号
// HSSFRow headerRow = (HSSFRow)sheet.CreateRow(rowsNum);
//HSSFCellStyle headStyle = (HSSFCellStyle)workbook.CreateCellStyle();
// headStyle.Alignment = (HorizontalAlignment)HorizontalAlignment.Center;
//设置列宽,excel列宽每个像素是1/256
//设置行高 ,excel行高度每个像素点是1/20 // headerRow.HeightInPoints = 0; // 表头高度
//HSSFFont font = (HSSFFont)workbook.CreateFont();
//font.FontHeightInPoints = 16;
//font.Boldweight = 100;
// headStyle.SetFont(font);
//只需要一列 2016-3-24 宽度像素是1/256
var widths = (int)(0.5 * 256);
sheet.SetColumnWidth(0, 14*256);//*256 1厘米=96/2.54≈37.8像素。
sheet.SetColumnWidth(1, widths);
sheet.SetColumnWidth(2, 25 * 256);//*256 1厘米=96/2.54≈37.8像素。
//填充数据行
HSSFRow row = null;
rowsNum = 0;
int rowindex = 0;
//设置下初始值
int dx1 = 0, dy1 = 0, dx2 = 0, dy2 = 0, col1 = 0, row1 = rowindex, col2 = 0, row2 = rowindex;
string qrcodestr = "";
string msg = "";
int hight = 0;
HSSFCellStyle cellStyle = (HSSFCellStyle)workbook.CreateCellStyle();//设置样式
HSSFFont cellfont = (HSSFFont)workbook.CreateFont(); //设置字体
cellStyle.Alignment = HorizontalAlignment.Left;
cellStyle.VerticalAlignment = VerticalAlignment.Top;//对齐方式
cellStyle.WrapText = true;//设置换行这个要先设置
cellfont.FontHeightInPoints = 10;//字体大小
cellfont.Boldweight = 200;//字体厚度
foreach (DataRow dr in dt.Rows)
{
//循环列的次数 只要五列 先加第一行为空 高度是实在的像素
row = (HSSFRow)sheet.CreateRow(rowsNum);
//row.HeightInPoints = 47;
row.HeightInPoints = 102;//111(int)3.92 * 38; 148
row.CreateCell(0, CellType.String).SetCellValue("");
rowindex++;
rowsNum++;
for (int i = 0; i < 5; i++)
{
// cellfont = (HSSFFont)workbook.CreateFont();
row = (HSSFRow)sheet.CreateRow(rowsNum);
var cell = row.CreateCell(2, CellType.String);
//赋值都是第一列 0
if (dr[i]!=dr["二维码"])//只要不是二维码字符串就跳过
{
if (dr[i].Equals(dr["商品名称"]))
{
cellfont.FontHeightInPoints = 9;
cellfont.Boldweight =200;
row.HeightInPoints = 33.75f;
cellStyle.SetFont(cellfont);
cell.CellStyle = cellStyle;
cell.SetCellValue(dr[i].ToString());
}
if (dr[i].Equals(dr["产地"]))
{
cellfont.FontHeightInPoints = 12;
cellfont.Boldweight = 200;
row.HeightInPoints = 33.75f;
cellStyle.SetFont(cellfont);
cell.CellStyle = cellStyle;
cell.SetCellValue(dr[i].ToString());
}
if (dr[i].Equals(dr["规格"]))
{
cellfont.Boldweight = 200;
cellfont.FontHeightInPoints = 12;
row.HeightInPoints = 33.75f;
cellStyle.SetFont(cellfont);
cell.CellStyle = cellStyle;
cell.SetCellValue(dr[i].ToString());
}
if (dr[i].Equals(dr["清关类型"]))
{
cellfont.FontHeightInPoints = 13;
cellfont.Boldweight = 700;
row.HeightInPoints = 33.75f;
cellStyle.SetFont(cellfont);
cell.CellStyle = cellStyle;
cell.SetCellValue(dr[i].ToString());
} }
else
{
row.HeightInPoints = 105;//高度是1/20
if (isexcel)
{
WebClient myWebClient = new WebClient();
string imagepathfix = imageBasePath + Guid.NewGuid().ToString();
string pfx = ".png";
if (dr[i].ToString().LastIndexOf(".jpg") > 0)
{
pfx = ".jpg";
}
else
{
}
string oldimagpath = imagepathfix + "1" + pfx;
strQrCodePath = imagepathfix + "." + pfx;
try
{
myWebClient.DownloadFile(dr[i].ToString(), oldimagpath);
}
catch (Exception exx)
{
msg += dr["商品名称"].ToString() + " 的二维码有问题," + exx.Message;
continue;
}
//处理下二维码大小
if (!string.IsNullOrEmpty(TextBox1.Text))
{
int.TryParse(TextBox1.Text.Trim(), out hight);
}
if (hight == 0)
hight = 102;
ImageClass.MakeThumbnail(oldimagpath, strQrCodePath, hight, hight, "H");
}
else
{
qrcodestr = "http://www.unions3.com/vshop/ProductDetails.aspx?productid="
+ dr[i].ToString();
strQrCodePath = GetQrCode(qrcodestr, false);
}
byte[] bytes = File.ReadAllBytes(strQrCodePath);
int pictureIdx = workbook.AddPicture(bytes, PictureType.JPEG);
// Create the drawing patriarch. This is the top level container for all shapes.
HSSFPatriarch patriarch = (HSSFPatriarch)sheet.CreateDrawingPatriarch();
row1 = rowindex;
row2 = rowindex;
//add a picture
#region nopi创建画图
// 通常,利用NPOI画图主要有以下几个步骤:
//1.创建一个Patriarch;
//2.创建一个Anchor,以确定图形的位置;
//3.调用Patriarch创建图形;
//4.设置图形类型(直线,矩形,圆形等)及样式(颜色,粗细等)。
//关于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;
#endregion
//(int)3.07*38 (int)3.92*38
dx1 = 0; dy1 = 0; dx2 = (int)3.07 * 38; dy2 = (int)3.92 * 38; col1 = 1; row1 = rowindex; col2 = 1; row2 = rowindex;
HSSFClientAnchor anchor = new HSSFClientAnchor(dx1, dy1, dx2, dy2, col1, row1, col2, row2);
HSSFPicture pict = (HSSFPicture)patriarch.CreatePicture(anchor, pictureIdx);
pict.Resize();
}
rowindex++;
rowsNum++;
} //删除图片文件
if (File.Exists(strQrCodePath))
{
File.Delete(strQrCodePath);
}
}
//供浏览器下载Excel
if (HttpContext.Current.Request.Browser.Browser == "IE")
FileName = HttpUtility.UrlEncode(FileName);
using (MemoryStream ms = new MemoryStream())
{
workbook.Write(ms);
ms.Flush();
ms.Position = 0;
HttpContext curContext = HttpContext.Current;
// 设置编码和附件格式
curContext.Response.ContentType = "application/vnd.ms-excel";
curContext.Response.ContentEncoding = Encoding.UTF8;
curContext.Response.Charset = "";
curContext.Response.AppendHeader("Content-Disposition",
"attachment;filename=" + HttpUtility.UrlEncode(FileName, Encoding.UTF8));
curContext.Response.BinaryWrite(ms.GetBuffer());
ms.Close();
ms.Dispose();
// curContext.Response.End();
HttpContext.Current.ApplicationInstance.CompleteRequest();
}
//}
//catch (Exception ex)
//{
if (!string.IsNullOrEmpty(msg))
{
Page.ClientScript.RegisterStartupScript(this.GetType(), "key", "<script>alert('" + msg + "');</script>");
}
else { } //}
}

  

/// <summary>        /// 增加二维码        /// </summary>        /// <param name="dt"></param>        /// <param name="isexcel"></param>        protected void AddPicture(DataTable dt, bool isexcel = true)        {
            if (!Directory.Exists(imageBasePath))            {                Directory.CreateDirectory(imageBasePath);            }            if (!Directory.Exists(excelBasePath))            {                Directory.CreateDirectory(excelBasePath);            }            //创建工作薄            HSSFWorkbook workbook = new HSSFWorkbook();            //create sheet            HSSFSheet sheet = (HSSFSheet)workbook.CreateSheet("二维码打印");            string FileName ="二维码"+DateTime.Now.ToString("yyyyMMddhhmmss") + ".xls";                    string strQrCodePath = "";            //填充列标题以及样式            int rowsNum = 0;  //行号           // HSSFRow headerRow = (HSSFRow)sheet.CreateRow(rowsNum);            //HSSFCellStyle headStyle = (HSSFCellStyle)workbook.CreateCellStyle();           // headStyle.Alignment = (HorizontalAlignment)HorizontalAlignment.Center;            //设置列宽,excel列宽每个像素是1/256            //设置行高 ,excel行高度每个像素点是1/20
           // headerRow.HeightInPoints = 0;   // 表头高度                             //HSSFFont font = (HSSFFont)workbook.CreateFont();            //font.FontHeightInPoints = 16;            //font.Boldweight = 100;           // headStyle.SetFont(font);            //只需要一列 2016-3-24  宽度像素是1/256            var widths = (int)(0.5 * 256);            sheet.SetColumnWidth(0, 14*256);//*256  1厘米=96/2.54≈37.8像素。            sheet.SetColumnWidth(1, widths);            sheet.SetColumnWidth(2, 25 * 256);//*256  1厘米=96/2.54≈37.8像素。            //填充数据行            HSSFRow row = null;            rowsNum = 0;               int rowindex = 0;            //设置下初始值             int dx1 = 0, dy1 = 0, dx2 = 0, dy2 = 0, col1 = 0, row1 = rowindex, col2 = 0, row2 = rowindex;            string qrcodestr = "";            string msg = "";            int hight = 0;            HSSFCellStyle cellStyle = (HSSFCellStyle)workbook.CreateCellStyle();//设置样式              HSSFFont cellfont = (HSSFFont)workbook.CreateFont();  //设置字体            cellStyle.Alignment =  HorizontalAlignment.Left;            cellStyle.VerticalAlignment = VerticalAlignment.Top;//对齐方式            cellStyle.WrapText = true;//设置换行这个要先设置            cellfont.FontHeightInPoints = 10;//字体大小            cellfont.Boldweight = 200;//字体厚度            foreach (DataRow dr in dt.Rows)            {                //循环列的次数    只要五列  先加第一行为空   高度是实在的像素                row = (HSSFRow)sheet.CreateRow(rowsNum);                //row.HeightInPoints = 47;                                     row.HeightInPoints = 102;//111(int)3.92 * 38;  148                row.CreateCell(0, CellType.String).SetCellValue("");                rowindex++;                rowsNum++;                for (int i = 0; i < 5; i++)                {                  //  cellfont = (HSSFFont)workbook.CreateFont();                    row = (HSSFRow)sheet.CreateRow(rowsNum);                    var cell = row.CreateCell(2, CellType.String);                                       //赋值都是第一列 0                    if (dr[i]!=dr["二维码"])//只要不是二维码字符串就跳过                    {                                            if (dr[i].Equals(dr["商品名称"]))                        {                            cellfont.FontHeightInPoints = 9;                            cellfont.Boldweight =200;                            row.HeightInPoints = 33.75f;                            cellStyle.SetFont(cellfont);                            cell.CellStyle = cellStyle;                            cell.SetCellValue(dr[i].ToString());                        }                        if (dr[i].Equals(dr["产地"]))                        {                            cellfont.FontHeightInPoints = 12;                            cellfont.Boldweight = 200;                            row.HeightInPoints = 33.75f;                            cellStyle.SetFont(cellfont);                            cell.CellStyle = cellStyle;                            cell.SetCellValue(dr[i].ToString());                        }                        if (dr[i].Equals(dr["规格"]))                        {                            cellfont.Boldweight = 200;                            cellfont.FontHeightInPoints = 12;                            row.HeightInPoints = 33.75f;                            cellStyle.SetFont(cellfont);                            cell.CellStyle = cellStyle;                            cell.SetCellValue(dr[i].ToString());                        }                        if (dr[i].Equals(dr["清关类型"]))                        {                            cellfont.FontHeightInPoints = 13;                             cellfont.Boldweight = 700;                            row.HeightInPoints = 33.75f;                            cellStyle.SetFont(cellfont);                            cell.CellStyle = cellStyle;                            cell.SetCellValue(dr[i].ToString());                        }                                                               }                    else                    {                        row.HeightInPoints = 105;//高度是1/20                        if (isexcel)                        {                            WebClient myWebClient = new WebClient();                            string imagepathfix = imageBasePath + Guid.NewGuid().ToString();                            string pfx = ".png";                            if (dr[i].ToString().LastIndexOf(".jpg") > 0)                            {                                pfx = ".jpg";                            }                            else                            {                            }                            string oldimagpath = imagepathfix + "1" + pfx;                            strQrCodePath = imagepathfix + "." + pfx;                            try                            {                                myWebClient.DownloadFile(dr[i].ToString(), oldimagpath);                            }                            catch (Exception exx)                            {                                msg += dr["商品名称"].ToString() + "  的二维码有问题," + exx.Message;                                continue;                            }                             //处理下二维码大小                                                        if (!string.IsNullOrEmpty(TextBox1.Text))                            {                                int.TryParse(TextBox1.Text.Trim(), out hight);                            }                            if (hight == 0)                                hight = 102;                            ImageClass.MakeThumbnail(oldimagpath, strQrCodePath, hight, hight, "H");                        }                        else                        {                            qrcodestr = "http://www.unions3.com/vshop/ProductDetails.aspx?productid="                                + dr[i].ToString();                            strQrCodePath = GetQrCode(qrcodestr, false);                        }                        byte[] bytes = File.ReadAllBytes(strQrCodePath);                        int pictureIdx = workbook.AddPicture(bytes, PictureType.JPEG);                        // Create the drawing patriarch.  This is the top level container for all shapes.                         HSSFPatriarch patriarch = (HSSFPatriarch)sheet.CreateDrawingPatriarch();                        row1 = rowindex;                        row2 = rowindex;                        //add a picture                        #region nopi创建画图                        //  通常,利用NPOI画图主要有以下几个步骤:                        //1.创建一个Patriarch;                        //2.创建一个Anchor,以确定图形的位置;                        //3.调用Patriarch创建图形;                        //4.设置图形类型(直线,矩形,圆形等)及样式(颜色,粗细等)。                        //关于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;                         #endregion                        //(int)3.07*38 (int)3.92*38                        dx1 = 0; dy1 = 0; dx2 = (int)3.07 * 38; dy2 = (int)3.92 * 38; col1 = 1; row1 = rowindex; col2 = 1; row2 = rowindex;                        HSSFClientAnchor anchor = new HSSFClientAnchor(dx1, dy1, dx2, dy2, col1, row1, col2, row2);                        HSSFPicture pict = (HSSFPicture)patriarch.CreatePicture(anchor, pictureIdx);                        pict.Resize();                    }                    rowindex++;                    rowsNum++;                }
                //删除图片文件                if (File.Exists(strQrCodePath))                {                    File.Delete(strQrCodePath);                }            }            //供浏览器下载Excel            if (HttpContext.Current.Request.Browser.Browser == "IE")                FileName = HttpUtility.UrlEncode(FileName);            using (MemoryStream ms = new MemoryStream())            {                workbook.Write(ms);                ms.Flush();                ms.Position = 0;                HttpContext curContext =  HttpContext.Current;                // 设置编码和附件格式                curContext.Response.ContentType = "application/vnd.ms-excel";                curContext.Response.ContentEncoding = Encoding.UTF8;                curContext.Response.Charset = "";                curContext.Response.AppendHeader("Content-Disposition",                     "attachment;filename=" + HttpUtility.UrlEncode(FileName, Encoding.UTF8));                curContext.Response.BinaryWrite(ms.GetBuffer());                ms.Close();                ms.Dispose();                // curContext.Response.End();                HttpContext.Current.ApplicationInstance.CompleteRequest();            }            //}            //catch (Exception ex)            //{            if (!string.IsNullOrEmpty(msg))            {                Page.ClientScript.RegisterStartupScript(this.GetType(), "key", "<script>alert('" + msg + "');</script>");            }            else
            {
            }
            //}        }

nopi 简洁笔记的更多相关文章

  1. C#的多线程简洁笔记

    New Thread(()=>{}).Start(); //匿名线程 Thread Ntd = new Thread(T1); Ntd.IsBackground = true; //后台线程 N ...

  2. Golang笔记(一)简洁的语言风格

    Golang笔记(一)简洁的语言风格 概述 Golang继承了很多C语言的风格,寡人使用了十几年C语言,切换到Golang时上手很快,并且随着深入的使用,越来越喜欢这门语言.Golang最直观的感受是 ...

  3. sass笔记-3|Sass基础语法之样式复用和保持简洁

    上一篇详述了Sass如何嵌套.导入和注释这3个基本方式来保持条理性和可读性,这一篇更进一步地阐述sass保持样式复用和简洁的方式--混合器和选择器继承--这两种方式都能复用样式,使用它们也不难,但一定 ...

  4. Java基础知识强化之集合框架笔记48:产生10个1~20之间的随机数(要求:随机数不能重复) 简洁版

    1. 编写一个程序,获取10个1至20的随机数,要求随机数不能重复. 分析:  A: 创建随机数对象  B: 创建一个HashSet集合  C: 判断集合的长度是不是小于10    是:就创建一个随机 ...

  5. Python笔记之不可不练

    如果您已经有了一定的Python编程基础,那么本文就是为您的编程能力锦上添花,如果您刚刚开始对Python有一点点兴趣,不怕,Python的重点基础知识已经总结在博文<Python笔记之不可不知 ...

  6. Python笔记之不可不知

    Python软件已经安装成功有很长一段时间了,也即或多或少的了解Python似乎也很长时间了,也是偏于各种借口,才在现在开始写点总结.起初接触Python是因为公司项目中需要利用Python来测试开发 ...

  7. Sass学习笔记之入门篇

    Sass又名SCSS,是CSS预处理器之一,,它能用来清晰地.结构化地描述文件样式,有着比普通 CSS 更加强大的功能. Sass 能够提供更简洁.更优雅的语法,同时提供多种功能来创建可维护和管理的样 ...

  8. 在线课程笔记—.NET基础

    关于学习北京理工大学金旭亮老师在线课程的笔记. 介绍: 在线课程网址:http://mooc.study.163.com/university/BIT#/c 老师个人网站:http://jinxuli ...

  9. Effective Java笔记一 创建和销毁对象

    Effective Java笔记一 创建和销毁对象 第1条 考虑用静态工厂方法代替构造器 第2条 遇到多个构造器参数时要考虑用构建器 第3条 用私有构造器或者枚举类型强化Singleton属性 第4条 ...

随机推荐

  1. webstorm中使用sass

    最近由原来的sublime转为使用webstorm,用的不是很熟.我们在webstorm中使用sass 1.首先sass是基于ruby的.这个时候我们需要安装ruby. 2.安装成功后.我们需要去掉原 ...

  2. Lua 求当前月份的最大天数

    [1]实现代码 -- 第一种方式:简写 , day = })) print('The first way result : dayAmount = ' .. dayAmount) -- 第二种方式:分 ...

  3. MySQL 5.6 (Win7 64位)下载、安装与配置图文教程

    一. 工具 Win7 64位操作系统 二. 步骤 第一步:下载安装包 下载 地址:http://www.mysql.com/ 截止到目前(2016/7/24) ,官网的最新版本是5.7.13,不过自己 ...

  4. nginx-编译安装 第一章

    nginx 第一章:编译安装 nginx 官网网站:http://nginx.org/en/ 1.基础说明 基本HTTP服务器功能其他HTTP服务器功能邮件代理服务器功能TCP/UDP代理服务器功能体 ...

  5. Linux tshark抓包

    使用tshark进行抓包 注:需要安装wireshar抓包工具 安装:yum -y install wireshark # 可以抓的包 命令:tshark # 抓取mysql查询 命令:tshark ...

  6. 2018-2019-2 20189206 Python3学习

    python3简明教程学习 基本概念 脚本文件: 脚本文件英文为Script.实际上脚本就是程序,一般都是由应用程序提供的编程语言.应用程序包括浏览器(javaScript.VBScript).多媒体 ...

  7. 【ASP.NET】 Config Error: This configuration section cannot be used at this path.

    Config Error: This configuration section cannot be used at this path. This happens when the section ...

  8. LeetCode in action

    (1) Linked List: 2-add-two-numbers,2.cpp 19-remove-nth-node-from-end-of-list,TBD 21-merge-two-sorted ...

  9. SAP Hybris电子商务最新功能

    SAP Hybris电子商务最新功能   SAP Hybris 电子商务6.0中国加速器是专为中国市场设计的电子商务平台,可满足企业在全渠道销售和订单履行方面的所有需求.新版的中国加速器基于SAP H ...

  10. 使用RStudio调试(debug)基础学习(一)

    点击行号的左侧,即可设置断点(或者按下Shift+F9),如果没有出现,反而出现下图的警告: 那么只是因为我的坏习惯--写一段脚本测试的时候都是新建,但不save到本地,不喜欢保存,写的差不多了才开始 ...