欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

C# 三种打印方式含代码

程序员文章站 2022-06-18 09:59:17
一:C#代码直接打印pdf文件(打印质保书pdf文件) 引用: 代码注释很详细了。 二:先生成excel在调用打印(生成excel主要在于布局) 按钮事件代码: PrintHelper.cs文件代码 生成的excel预览 三 在Visual Studio中通过插件编辑rdlc文件进行可视化布局(动态 ......

 

 

 

C# 三种打印方式含代码

 

 

一:c#代码直接打印pdf文件(打印质保书pdf文件)

引用:

C# 三种打印方式含代码

 

代码注释很详细了。

        private void btn_pdf_click(object sender, routedeventargs e)
        {
            string filepath = system.appdomain.currentdomain.setupinformation.applicationbase + "resource\\川ax5572 904080d005000.pdf";
            printshow(filepath);
        }

        /// <summary>
        /// 打印的代码
        /// </summary>
        /// <param name="url">要打印的pdf路径</param>
        private int printshow(string url)
        {
            int isok = 0;
            pdffile file = pdffile.open(url);
            printersettings settings = new printersettings();
            system.drawing.printing.printdocument pd = new system.drawing.printing.printdocument();
            settings.printername = "npi84ffaf (hp laserjet mfp m436)"; // 打印机名称
            settings.printtofile = false;

            //设置纸张大小(可以不设置,取默认设置)3.90 in,  8.65 in
            papersize ps = new papersize("test", 4, 9);
            ps.rawkind = 9; //如果是自定义纸张,就要大于118,(a4值为9,详细纸张类型与值的对照请看http://msdn.microsoft.com/zh-tw/library/system.drawing.printing.papersize.rawkind(v=vs.85).aspx)

            o2s.components.pdfrender4net.printing.pdfprintsettings pdfprintsettings = new o2s.components.pdfrender4net.printing.pdfprintsettings(settings);
            pdfprintsettings.papersize = ps;
            pdfprintsettings.pagescaling = o2s.components.pdfrender4net.printing.pagescaling.fittoprintermarginsproportional;
            pdfprintsettings.printersettings.copies = 1;

            try
            {
                file.print(pdfprintsettings);
                isok = 1;
            }
            catch (exception)
            {
                isok = -1;
                throw;
            }
            finally
            {

                file.dispose();
            }
            return isok;
        }

  

二:先生成excel在调用打印(生成excel主要在于布局)

按钮事件代码:

        private void btn_zbs_click(object sender, routedeventargs e)
        {
            // 准备好数据
            list<dynamicmodel> dm = new list<dynamicmodel>()
            {
                new dynamicmodel(){batchnumber="319040027",relmpa = "470",rmpa = "655",a="29.0",agt = "16.0",rmrel = "1.40",relrel = "1.18",directbendingone="",resultone = "",directbendingtwo = "i",
                    resulttwo = "合格",
                    metallography = "合格",
                    weightdeviation="合格",
                    surfacequality="合格",
                    sizeandappearance="合格",
                    packing="合格",
                },
                new dynamicmodel(){batchnumber="319040027",relmpa = "450",rmpa = "650",a="27.0",agt = "15.4",rmrel = "1.45",relrel = "1.13",directbendingone="",resultone = "",directbendingtwo = "i",
                    resulttwo = "合格",
                    metallography = "合格",
                    weightdeviation="合格",
                    surfacequality="合格",
                    sizeandappearance="合格",
                    packing="合格",
                },
                new dynamicmodel(){batchnumber="319040027",relmpa = "435",rmpa = "640",a="28.0",agt = "15.7",rmrel = "1.47",relrel = "1.09",directbendingone="",resultone = "",directbendingtwo = "i",
                    resulttwo = "合格",
                    metallography = "合格",
                    weightdeviation="合格",
                    surfacequality="合格",
                    sizeandappearance="合格",
                    packing="合格",
                },
                new dynamicmodel(){batchnumber="319040027",relmpa = "460",rmpa = "645",a="26.0",agt = "16.2",rmrel = "1.40",relrel = "1.15",directbendingone="",resultone = "",directbendingtwo = "i",
                    resulttwo = "合格",
                    metallography = "合格",
                    weightdeviation="合格",
                    surfacequality="合格",
                    sizeandappearance="合格",
                    packing="合格",
                },
                new dynamicmodel(){batchnumber="319040027",relmpa = "470",rmpa = "655",a="29.0",agt = "16.0",rmrel = "1.40",relrel = "1.18",directbendingone="",resultone = "",directbendingtwo = "i",
                    resulttwo = "合格",
                    metallography = "合格",
                    weightdeviation="合格",
                    surfacequality="合格",
                    sizeandappearance="合格",
                    packing="合格",
                },
            };

            list<chemistrymodel> cm = new list<chemistrymodel>()
            {
                new chemistrymodel(){batchnumber="319040027",bales="2",constituent="熔炼",c="0.22",si= "0.37",mn = "1.32",p="0.020",s="0,030",ceq = "0.46"},
                new chemistrymodel(){batchnumber="319040027",bales="2",constituent="熔炼",c="0.22",si= "0.37",mn = "1.32",p="0.020",s="0,030",ceq = "0.46"},
                new chemistrymodel(){batchnumber="319040027",bales="2",constituent="熔炼",c="0.22",si= "0.37",mn = "1.32",p="0.020",s="0,030",ceq = "0.46"},
                new chemistrymodel(){batchnumber="319040027",bales="2",constituent="熔炼",c="0.22",si= "0.37",mn = "1.32",p="0.020",s="0,030",ceq = "0.46"},
            };

            warrantymodel wm = new warrantymodel()
            {
                licencenumber = "xk05-001-00066",
                orderunit = "。。。。。。限公司",
                receivingunit = "。。。。有限责任公司",
                contractcode = "d9s0379001",
                varietyname = "钢筋混凝土用热轧带肋钢筋(盘卷)",
                technical = "gb/t1499.2-2018",
                fixedlength = "",
                brandname = "hrb400r",
                diameter = "10",
                addresschina = " 中   国   攀   枝   花",
                addressenglish = " pan zhi hua china ",
                knotnumber = "904080d005000",
                deliverystute = "热扎",
                certificateno = "1904db00384",
                arrivestation = "汽车自提",
                licensenumber = "川a09901",
                delivergoodsdata = "2019年4月8日",
                tabulationtime = "2019年04月08日 15时08分13分",
                remark = "\n1、兹证明本产品按供货标准检验各项指标均符合供货标准规定。     \n2、质量证明书原件是验收依据,复印件仅供参考,不作为验收凭证。     \n3、弯芯直径①:c▁d=a、g▁3d、h▁4d、i▁5d、j▁6d、k▁7d、l▁8d、m▁9d。",
                explain = "",
                personincharge = ""
            };
            wm.dynamic = dm;
            wm.chemistry = cm;

            // 调用打印
            printhelper printhelper = new printhelper(wm);
            printhelper.datatoexcel();

        }

  

 printhelper.cs文件代码

    /// <summary>
    /// 打印
    /// </summary>
    public class printhelper
    {

        /// <summary>
        /// 文件生成路径
        /// </summary>
        private string _filepath = system.appdomain.currentdomain.setupinformation.applicationbase + "file\\" +
                                   datetime.now.tostring("yyyymmddhhmmss");//datetime.now.tofiletimeutc().tostring();
        /// <summary>
        /// 打印质保书数据实体
        /// </summary>
        private warrantymodel _warranty;

        /// <summary>
        /// 
        /// </summary>
        private int _maxremarklength = int.minvalue;

        public printhelper(warrantymodel warranty)
        {
            _warranty = warranty;
        }
        /// <summary>
        /// 动态生成excel
        /// </summary>
        public void datatoexcel()
        {

            int max = int.minvalue;
            var remarklist = _warranty.chemistry.select(m => m.batchnumber).tolist();
            for (int i = 0, length = remarklist.count; i < length; i++)
            {
                var remark = remarklist[i];
                if (remark != null && remark.length > max)
                {
                    max = remarklist[i].length;
                }
            }

            if (max > 10) _maxremarklength = (max / 4 + 1) * 20;
            else _maxremarklength = 40;

            application excelapp = new application();

            workbook worksbook = excelapp.workbooks.add();
            worksheet worksheet = (worksheet)worksbook.worksheets[1];
            if (worksheet == null)
            {
                system.diagnostics.debug.writeline("error: worksheet == null");
                return;
            }

            worksheet.name = "deliveryorderbills";
            worksheet.cells.wraptext = true;
            worksheet.cells.entirerow.autofit();

            rangemark(worksheet, "a1", "d1", "qg/js jl(y)042-2017", 10, 30, 1, 0);
            rangemark(worksheet, "h1", "k1", "产 品 质 量 保 证 书", 26, 30, 3, 0);

            rangemark(worksheet, "a3", "a3", "许可证号:", 12, 30, 3, 0);
            rangemark(worksheet, "b3", "d3", _warranty.licencenumber, 12, 30, 1, 0);
            rangemark(worksheet, "o3", "o3", "结齐单号:", 12, 30, 3, 0);
            rangemark(worksheet, "p3", "q3", _warranty.knotnumber, 12, 30, 1, 0);

            rangemark(worksheet, "a4", "a4", "订货单位:", 12, 30, 3, 0);
            rangemark(worksheet, "b4", "c4", _warranty.orderunit, 12, 30, 1, 0);
            rangemark(worksheet, "i4", "k4", "quality  certificate", 12, 30, 3, 0);
            rangemark(worksheet, "o4", "o4", "交货状态:", 12, 30, 3, 0);
            rangemark(worksheet, "p4", "q4", _warranty.deliverystute, 12, 30, 1, 0);

            rangemark(worksheet, "a5", "a5", "收获单位:", 12, 30, 3, 0);
            rangemark(worksheet, "b5", "c5", _warranty.receivingunit, 12, 30, 1, 0);
            rangemark(worksheet, "h5", "k5", "攀钢集团攀枝花金属制品有限公司", 16, 30, 3, 0);
            rangemark(worksheet, "o5", "o5", "证明书号:", 12, 30, 3, 0);
            rangemark(worksheet, "p5", "q5", _warranty.certificateno, 12, 30, 1, 0);

            rangemark(worksheet, "a6", "a6", "合同编号:", 12, 30, 3, 0);
            rangemark(worksheet, "b6", "c6", _warranty.contractcode, 12, 30, 1, 0);
            rangemark(worksheet, "f6", "f6", "定尺长度\n(mm):", 12, 30, 3, 0);
            rangemark(worksheet, "g6", "g6", _warranty.fixedlength, 12, 30, 3, 0);
            rangemark(worksheet, "i6", "m6", "pangang group panzhihua metal products co., ltd.", 12, 20, 3, 0);
            rangemark(worksheet, "o6", "o6", "到 站:", 12, 30, 3, 0);
            rangemark(worksheet, "p6", "q6", _warranty.arrivestation, 12, 30, 1, 0);

            rangemark(worksheet, "a7", "a7", "品种名称:", 12, 30, 3, 0);
            rangemark(worksheet, "b7", "d7", _warranty.varietyname, 12, 30, 1, 0);
            rangemark(worksheet, "f7", "f7", "牌 号", 12, 30, 3, 0);
            rangemark(worksheet, "g7", "g7", _warranty.brandname, 12, 20, 3, 0);
            rangemark(worksheet, "j7", "j7", "地 址:", 12, 30, 3, 0);
            rangemark(worksheet, "k7", "m7", _warranty.addresschina, 12, 30, 3, 0);
            rangemark(worksheet, "o7", "o7", "车 号:", 12, 30, 3, 0);
            rangemark(worksheet, "p7", "q7", _warranty.licensenumber, 12, 30, 1, 0);

            rangemark(worksheet, "a8", "a8", "技术条件:", 12, 30, 3, 0);
            rangemark(worksheet, "b8", "d8", _warranty.technical, 12, 30, 1, 0);
            rangemark(worksheet, "f8", "f8", "直径(mm):", 12, 30, 3, 0);
            rangemark(worksheet, "g8", "g8", _warranty.diameter, 12, 30, 3, 0);
            rangemark(worksheet, "j8", "j8", "address:", 12, 30, 3, 0);
            rangemark(worksheet, "k8", "m8", _warranty.addressenglish, 12, 30, 3, 0);
            rangemark(worksheet, "o8", "o8", "发货日期:", 12, 30, 3, 0);
            rangemark(worksheet, "p8", "q8", _warranty.delivergoodsdata, 12, 30, 1, 0);

            // 化学成分表单(表头部分)
            rangemark(worksheet, "a9", "a10", "批号");
            rangemark(worksheet, "b9", "b10", "捆(包)数");
            rangemark(worksheet, "c9", "c10", "成分项目");
            rangemark(worksheet, "d9", "o9", "化  学  成  分 chemical composition");
            rangemark(worksheet, "p9", "p9", "");
            rangemark(worksheet, "q9", "q9", "");
            rangemark(worksheet, "r9", "r9", "");

            rangemark(worksheet, "d10", "d10", "c");
            rangemark(worksheet, "e10", "e10", "si");
            rangemark(worksheet, "f10", "f10", "mn");
            rangemark(worksheet, "g10", "g10", "p");
            rangemark(worksheet, "h10", "h10", "s");
            rangemark(worksheet, "i10", "i10", "ceq");
            rangemark(worksheet, "j10", "j10", "");
            rangemark(worksheet, "k10", "k10", "");
            rangemark(worksheet, "l10", "l10", "");
            rangemark(worksheet, "m10", "m10", "");
            rangemark(worksheet, "n10", "n10", "");
            rangemark(worksheet, "o10", "o10", "");
            rangemark(worksheet, "p10", "r10", "");

            // 化学成分表单(内容部分)
            var rowtwonum = 0;// 力学性能表单开始行索引

            if (_warranty.chemistry.any())
            {
                for (int i = 0; i < _warranty.chemistry.count; i++)
                {
                    // 行数索引
                    var rowonenum = 11 + i;
                    // 数据实体
                    var item = _warranty.chemistry[i];
                    rangemark(worksheet, string.format("a{0}", rowonenum), string.format("a{0}", rowonenum), item.batchnumber);
                    rangemark(worksheet, string.format("b{0}", rowonenum), string.format("b{0}", rowonenum), item.bales);
                    rangemark(worksheet, string.format("c{0}", rowonenum), string.format("c{0}", rowonenum), item.constituent);
                    rangemark(worksheet, string.format("d{0}", rowonenum), string.format("d{0}", rowonenum), item.c);
                    rangemark(worksheet, string.format("e{0}", rowonenum), string.format("e{0}", rowonenum), item.si);
                    rangemark(worksheet, string.format("f{0}", rowonenum), string.format("f{0}", rowonenum), item.mn);
                    rangemark(worksheet, string.format("g{0}", rowonenum), string.format("g{0}", rowonenum), item.p);
                    rangemark(worksheet, string.format("h{0}", rowonenum), string.format("h{0}", rowonenum), item.s);
                    rangemark(worksheet, string.format("i{0}", rowonenum), string.format("i{0}", rowonenum), item.ceq);
                    rangemark(worksheet, string.format("j{0}", rowonenum), string.format("j{0}", rowonenum), "");
                    rangemark(worksheet, string.format("k{0}", rowonenum), string.format("k{0}", rowonenum), "");
                    rangemark(worksheet, string.format("l{0}", rowonenum), string.format("l{0}", rowonenum), "");
                    rangemark(worksheet, string.format("m{0}", rowonenum), string.format("m{0}", rowonenum), "");
                    rangemark(worksheet, string.format("n{0}", rowonenum), string.format("n{0}", rowonenum), "");
                    rangemark(worksheet, string.format("o{0}", rowonenum), string.format("o{0}", rowonenum), "");
                    rangemark(worksheet, string.format("p{0}", rowonenum), string.format("p{0}", rowonenum), "");
                    rangemark(worksheet, string.format("q{0}", rowonenum), string.format("q{0}", rowonenum), "");
                    rangemark(worksheet, string.format("r{0}", rowonenum), string.format("r{0}", rowonenum), "");
                }
                // 空行索引
                var krowindex = _warranty.chemistry.count + 11;
                rangemark(worksheet, string.format("a{0}", krowindex), string.format("r{0}", krowindex), "", 12, 15);
                rowtwonum = krowindex + 1;
            }
            else
            {
                rangemark(worksheet, string.format("a{0}", 11), string.format("r{0}", 11), "", 12, 15);
                rowtwonum = 12;
            }
            // 力学性能表单(表头部分)
            rangemark(worksheet, string.format("a{0}", rowtwonum), string.format("a{0}", rowtwonum + 1), "批号");
            rangemark(worksheet, string.format("b{0}", rowtwonum), string.format("g{0}", rowtwonum), "力学性能");
            rangemark(worksheet, string.format("h{0}", rowtwonum), string.format("i{0}", rowtwonum), "冷弯 / 180°");
            rangemark(worksheet, string.format("j{0}", rowtwonum), string.format("k{0}", rowtwonum), "反向弯曲 ②");

            rangemark(worksheet, string.format("l{0}", rowtwonum), string.format("l{0}", rowtwonum + 1), "金相组织");
            rangemark(worksheet, string.format("m{0}", rowtwonum), string.format("m{0}", rowtwonum + 1), "");
            rangemark(worksheet, string.format("n{0}", rowtwonum), string.format("n{0}", rowtwonum + 1), "");
            rangemark(worksheet, string.format("o{0}", rowtwonum), string.format("o{0}", rowtwonum + 1), "重量偏差");
            rangemark(worksheet, string.format("p{0}", rowtwonum), string.format("p{0}", rowtwonum + 1), "表面质量");
            rangemark(worksheet, string.format("q{0}", rowtwonum), string.format("q{0}", rowtwonum + 1), "尺寸和\n外形");
            rangemark(worksheet, string.format("r{0}", rowtwonum), string.format("r{0}", rowtwonum + 1), "包装");

            rangemark(worksheet, string.format("b{0}", rowtwonum + 1), string.format("b{0}", rowtwonum + 1), "rel /mpa");
            rangemark(worksheet, string.format("c{0}", rowtwonum + 1), string.format("c{0}", rowtwonum + 1), "rm /mpa");
            rangemark(worksheet, string.format("d{0}", rowtwonum + 1), string.format("d{0}", rowtwonum + 1), "a / %");
            rangemark(worksheet, string.format("e{0}", rowtwonum + 1), string.format("e{0}", rowtwonum + 1), "rgt / %");
            rangemark(worksheet, string.format("f{0}", rowtwonum + 1), string.format("f{0}", rowtwonum + 1), " r°m / r°el");
            rangemark(worksheet, string.format("g{0}", rowtwonum + 1), string.format("g{0}", rowtwonum + 1), "r°el/rel");
            rangemark(worksheet, string.format("h{0}", rowtwonum + 1), string.format("h{0}", rowtwonum + 1), "弯芯直径①");
            rangemark(worksheet, string.format("i{0}", rowtwonum + 1), string.format("i{0}", rowtwonum + 1), "结果");
            rangemark(worksheet, string.format("j{0}", rowtwonum + 1), string.format("j{0}", rowtwonum + 1), "弯芯直径①");
            rangemark(worksheet, string.format("k{0}", rowtwonum + 1), string.format("k{0}", rowtwonum + 1), "结果");

            // 力学性能表单(内容部分)
            var totalrowindex = rowtwonum + 2;// 统计行索引

            if (_warranty.dynamic.any())
            {
                for (int i = 0; i < _warranty.dynamic.count; i++)
                {
                    // 内容索引
                    var rowthreenum = i + rowtwonum + 2;
                    totalrowindex = rowthreenum + 1;
                    // 数据实体
                    var item = _warranty.dynamic[i];
                    rangemark(worksheet, string.format("a{0}", rowthreenum), string.format("a{0}", rowthreenum), item.batchnumber);
                    rangemark(worksheet, string.format("b{0}", rowthreenum), string.format("b{0}", rowthreenum), item.relmpa);
                    rangemark(worksheet, string.format("c{0}", rowthreenum), string.format("c{0}", rowthreenum), item.rmpa);
                    rangemark(worksheet, string.format("d{0}", rowthreenum), string.format("d{0}", rowthreenum), item.a);
                    rangemark(worksheet, string.format("e{0}", rowthreenum), string.format("e{0}", rowthreenum), item.agt);
                    rangemark(worksheet, string.format("f{0}", rowthreenum), string.format("f{0}", rowthreenum), item.rmrel);
                    rangemark(worksheet, string.format("g{0}", rowthreenum), string.format("g{0}", rowthreenum), item.relrel);
                    rangemark(worksheet, string.format("h{0}", rowthreenum), string.format("h{0}", rowthreenum), item.directbendingone);
                    rangemark(worksheet, string.format("i{0}", rowthreenum), string.format("i{0}", rowthreenum), item.resultone);
                    rangemark(worksheet, string.format("j{0}", rowthreenum), string.format("j{0}", rowthreenum), item.directbendingtwo);
                    rangemark(worksheet, string.format("k{0}", rowthreenum), string.format("k{0}", rowthreenum), item.resulttwo);
                    rangemark(worksheet, string.format("l{0}", rowthreenum), string.format("l{0}", rowthreenum), item.metallography);
                    rangemark(worksheet, string.format("m{0}", rowthreenum), string.format("m{0}", rowthreenum), "");
                    rangemark(worksheet, string.format("n{0}", rowthreenum), string.format("n{0}", rowthreenum), "");
                    rangemark(worksheet, string.format("o{0}", rowthreenum), string.format("o{0}", rowthreenum), item.weightdeviation);
                    rangemark(worksheet, string.format("p{0}", rowthreenum), string.format("p{0}", rowthreenum), item.surfacequality);
                    rangemark(worksheet, string.format("q{0}", rowthreenum), string.format("q{0}", rowthreenum), item.sizeandappearance);
                    rangemark(worksheet, string.format("r{0}", rowthreenum), string.format("r{0}", rowthreenum), item.packing);

                }
                 
            }
            // 添加统计行 
            rangemark(worksheet, string.format("a{0}", totalrowindex), string.format("a{0}", totalrowindex), "");
            rangemark(worksheet, string.format("b{0}", totalrowindex), string.format("b{0}", totalrowindex), "总捆(包)数 ");
            rangemark(worksheet, string.format("c{0}", totalrowindex), string.format("c{0}", totalrowindex), "计算");
            rangemark(worksheet, string.format("d{0}", totalrowindex), string.format("d{0}", totalrowindex), "");
            rangemark(worksheet, string.format("e{0}", totalrowindex), string.format("e{0}", totalrowindex), "");
            rangemark(worksheet, string.format("f{0}", totalrowindex), string.format("f{0}", totalrowindex), "");
            rangemark(worksheet, string.format("g{0}", totalrowindex), string.format("g{0}", totalrowindex), "");
            rangemark(worksheet, string.format("h{0}", totalrowindex), string.format("i{0}", totalrowindex), "实际总重量(t)");
            rangemark(worksheet, string.format("j{0}", totalrowindex), string.format("j{0}", totalrowindex), "计算");
            rangemark(worksheet, string.format("k{0}", totalrowindex), string.format("l{0}", totalrowindex), "");
            rangemark(worksheet, string.format("m{0}", totalrowindex), string.format("n{0}", totalrowindex), "");
            rangemark(worksheet, string.format("o{0}", totalrowindex), string.format("q{0}", totalrowindex), "");
            rangemark(worksheet, string.format("r{0}", totalrowindex), string.format("r{0}", totalrowindex), "");

            

            // 合并横着的单元格
            columnsspan(worksheet, "f1", "g1");
            columnsspan(worksheet, "f2", "g2");
            columnsspan(worksheet, "f3", "g3");
            columnsspan(worksheet, "f4", "g4");
            columnsspan(worksheet, "f5", "g5");

            columnsspan(worksheet, "l1", "m1");
            columnsspan(worksheet, "l2", "m2");
            columnsspan(worksheet, "l3", "m3");
            columnsspan(worksheet, "l4", "m4");
            columnsspan(worksheet, "l5", "m5");


            // 合并竖着的单元格 
            rowsspan(worksheet, "f1", "f5");
            rowsspan(worksheet, "g1", "g5");

            rowsspan(worksheet, "l1", "l5");
            rowsspan(worksheet, "m1", "m5");

            // 插入图片
            savepic(worksheet, "g1", directory.getcurrentdirectory() + "/pq.jpg");
            savepic(worksheet, "l1", directory.getcurrentdirectory() + "/s.jpg");

            //------------------------打印页面相关设置--------------------------------
            worksheet.pagesetup.papersize = microsoft.office.interop.excel.xlpapersize.xlpapera4;//纸张大小
            worksheet.pagesetup.orientation = microsoft.office.interop.excel.xlpageorientation.xllandscape;//页面横向
            //worksheet.pagesetup.zoom = 75; //打印时页面设置,缩放比例百分之几
            worksheet.pagesetup.zoom = false; //打印时页面设置,必须设置为false,页高,页宽才有效
            worksheet.pagesetup.fittopageswide = 1; //设置页面缩放的页宽为1页宽
            worksheet.pagesetup.fittopagestall = false; //设置页面缩放的页高自动
            worksheet.pagesetup.centerfooter = "第 &p 页,共 &n 页";//页面下标
            worksheet.pagesetup.footermargin = 5;
            worksheet.pagesetup.printgridlines = false; //打印单元格网线
            worksheet.pagesetup.topmargin = 15; //上边距为2cm(转换为in)
            worksheet.pagesetup.bottommargin = 20; //下边距为1.5cm
            worksheet.pagesetup.leftmargin = 30; //左边距为2cm
            worksheet.pagesetup.rightmargin = 30; //右边距为2cm
            worksheet.pagesetup.centerhorizontally = true; //文字水平居中
            //------------------------打印页面设置结束--------------------------------
            ///http://blog.csdn.net/wanmingtom/article/details/6125599
            ///
             

            // 生成excel文件
            worksheet.saveas(_filepath, type.missing, type.missing, type.missing, xlsaveasaccessmode.xlnochange, 1, false, type.missing, type.missing, type.missing); //另存表

            //// 直接打印放开下面两个注释即可
            //excelapp.visible = false; //是否显示excel文档
            //worksheet.printoutex();
            killprocess(excelapp); //杀掉生成的进程
            gc.collect(); //垃圾回收机制
             
        }

        private void columnsspan(worksheet worksheet, string start, string end)
        {
            microsoft.office.interop.excel.range eg1 = worksheet.get_range(start, end);
            eg1.mergecells = true;
            eg1.verticalalignment = microsoft.office.interop.excel.xlvalign.xlvaligncenter;
            eg1.horizontalalignment = microsoft.office.interop.excel.xlvalign.xlvaligncenter;

        }
        private void rowsspan(worksheet worksheet, string start, string end)
        {
            range pqpricrange = worksheet.get_range(start, end);
            pqpricrange.application.displayalerts = false;
            //pqpricrange.merge(missing.value);
            pqpricrange.mergecells = true;
            pqpricrange.application.displayalerts = true;
            pqpricrange.verticalalignment = microsoft.office.interop.excel.xlvalign.xlvaligncenter;
            pqpricrange.horizontalalignment = microsoft.office.interop.excel.xlvalign.xlvaligncenter;
        }


        /// <summary>
        /// 创建单元格
        /// </summary>
        /// <param name="worksheet">worksheet对象</param>
        /// <param name="startcell">开始格子号</param>
        /// <param name="endcell">终止格子号</param>
        /// <param name="strtext">文本</param>
        /// <param name="fontsize">字体大小</param>
        /// <param name="rowheight">行高</param>
        /// <param name="horizontalalignment">横向剧中</param>
        /// <param name="linestyle">单元格边框</param>
        /// <returns></returns>
        private bool rangemark(worksheet worksheet, string startcell, string endcell, string strtext, int fontsize = 12, int rowheight = 30, int horizontalalignment = 3, int linestyle = 1)
        {
            //创建一个区域对象。第一个参数是开始格子号,第二个参数是终止格子号。比如选中a1——d3这个区域。
            range range = worksheet.get_range(startcell, endcell);
            if (range == null)
            {
                system.diagnostics.debug.writeline("error: range == null");
                return false;
            }
            range.merge(0); //合并方法,0的时候直接合并为一个单元格
            range.font.size = fontsize; //字体大小
            range.font.name = "黑体"; //字体
            //range.entirerow.autofit(); //自动调整行高
            //range.entirecolumn.autofit();
            //range.rowheight = 20; 
            //range.entirecolumn.autofit(); //自动调整列宽
            //range.numberformatlocal = "@";
            //range.entirecolumn.autofit();
            range.numberformatlocal = "@";
            range.rowheight = rowheight;
            range.columnwidth = 15;
            //range.entirecolumn.autofit();
            //range.entirerow.autofit();
            range.horizontalalignment = horizontalalignment; //横向居中
            range.verticalalignment = xlvalign.xlvaligncenter;
            range.value = strtext; //合并单元格之后,设置其中的文本
            range.cells.borders.linestyle = linestyle; //设置单元格边框的粗细
            range.wraptext = true; //文本自动换行
            return true;
        }


        /// <summary>
        /// 杀掉生成的进程
        /// </summary>
        /// <param name="appobject">进程程对象</param>
        private static void killprocess(microsoft.office.interop.excel.application appobject)
        {
            int pid = 0;
            intptr hwnd = new intptr(appobject.hwnd);
            system.diagnostics.process p = null;
            try
            {
                getwindowthreadprocessid(hwnd, out pid);
                p = system.diagnostics.process.getprocessbyid(pid);
                if (p != null)
                {
                    p.kill();
                    p.dispose();
                }
            }
            catch (exception ex)
            {
                system.diagnostics.debug.writeline("进程关闭失败!异常信息:" + ex);
            }
        }

        /// <summary>
        /// 引用windows句柄,获取程序pid
        /// </summary>
        /// <param name="hwnd"></param>
        /// <param name="pid"></param>
        /// <returns></returns>
        [dllimport("user32.dll")]
        public static extern int getwindowthreadprocessid(intptr hwnd, out int pid);

        private void savepic(worksheet worksheet, string rangename, string filename)
        {
            microsoft.office.interop.excel.range range = worksheet.get_range(rangename, type.missing);
            range.select();
            range.horizontalalignment = microsoft.office.interop.excel.xlvalign.xlvaligncenter;
            ///////////  
            float picleft, pictop, picwidth, picheight;    //距离左边距离,顶部距离,图片宽度、高度  
            pictop = convert.tosingle(range.top);
            picwidth = convert.tosingle(range.mergearea.width);
            picheight = convert.tosingle(range.height);
            picwidth = convert.tosingle(range.width);
            picleft = convert.tosingle(range.left);
            //////////////////  

            microsoft.office.interop.excel.pictures pict = (microsoft.office.interop.excel.pictures)worksheet.pictures(type.missing);
            if (filename.indexof(".") > 0)
            {
                if (system.io.file.exists(filename))
                {
                    pict.insert(filename, type.missing);//显示原图   重叠在一起  
                    //worksheet.shapes.addpicture(filename,
                    //    microsoft.office.core.msotristate.msofalse,
                    //    microsoft.office.core.msotristate.msoctrue,
                    //    picleft, pictop, picwidth, picheight);//指定位置显示小图  
                }
            }
        }
    }

  生成的excel预览

C# 三种打印方式含代码

 

三 在visual studio中通过插件编辑rdlc文件进行可视化布局(动态添加行的我暂时没有弄出来,这里只演示固定字段的打印)

 首先引用:

C# 三种打印方式含代码

 

C# 三种打印方式含代码

第一步:安装插件 

C# 三种打印方式含代码

搜索rdlc

 C# 三种打印方式含代码

 第二步:这里下载好之后从新启动vs它会自动安装插件。安装好后创建文件。

 

 C# 三种打印方式含代码

 

C# 三种打印方式含代码

 

 第三步:可视化布局操作

 

C# 三种打印方式含代码

 

 第四步:设置数据绑定,在需要绑定数据的单元格中鼠标右键点击文本框属性。

 

C# 三种打印方式含代码

 

名称:与实体属性写法一致  值:[与实体属性写法一致]

 C# 三种打印方式含代码

设置字体及大小

 

C# 三种打印方式含代码

 

 第五步:布局及所有字段写好之后就设置数据集(我这里用的是本地实体模型)

右键添加数据集

 

C# 三种打印方式含代码

C# 三种打印方式含代码

这里选择你要绑定的实体

 

C# 三种打印方式含代码

 

 C# 三种打印方式含代码

C# 三种打印方式含代码

 

注意:当界面设计好之后我们重新生成项目总是提示生成失败,而vs也不提示哪里出错了。

C# 三种打印方式含代码

我就猜测是不是这个rdlc文件的问题,我就试着把rdlc文件排除在项目外,再次生成就可以了。

C# 三种打印方式含代码

当然这个不影响我们编辑rdlc文件,你可以继续编辑,只不过在读取的时候,是默认bin目录下,这里每次编辑了就要手动赋值到bin目录中。 

 这里设计好了之后就看代码。

按钮事件代码:

  private void btn_code_click(object sender, routedeventargs e)
        {
            // 数据
            var csm = new codesheetmodel()
            {
                codesheetnumber = "1w52902644",
                contractnuber = "d8s0363501",
                quasisign = "",
                loadingpoint = "北部站",
                deliverystandard = "gb/t1499.2-2019",
                deliveryaddress = "",
                orderunit = "。。。。。有限公司",
                receivingunit = "。。。。。。。有限公司",
                settlementunit = "。。。。。有限公司",
                privatelinename = "螺纹钢",
                licensenumber = "川b37037",
                billloadno = "1w62904010501",
                shipptype = "21",
                deliveryclass = "2",
                productdescription = "不说明",
                varietyname = "螺纹钢",
                shipmentno = "",
                brandno = "hrb400e1114",
                factoryoutdata = "2019-04-03 14:10",
                metermode = "计量",
                printdatetime = "2019-04-03 14:10:45"
            };

            var p = new codeprinthelper(); 
            p.run(csm, (ex) =>
            {
                messagebox.show(ex.message);
            }, "npi84ffaf (hp laserjet mfp m436)");
             
            messagebox.show("完成打印。。。");
        }

  codeprinthelper.cs文件代码:

    /// <summary>
    /// 码单打印
    /// </summary>
    public class codeprinthelper
    {

        /// <summary>
        /// 用来记录当前打印到第几页了
        /// </summary>
        private int m_currentpageindex = 0;
        private ilist<stream> m_streams;
        /// <summary>
        /// 时间
        /// </summary>
        private datetime datetime;

        /// <summary>
        /// 打印机集合
        /// </summary>
        private static list<string> printlist = null;

        /// <summary>
        /// 打印发生异常的回调函数
        /// </summary>
        public action<exception> execptioncallback { get; set; }

        /// <summary>
        /// 获取打印机集合
        /// </summary>
        public static list<string> printlist
        {
            get
            {
                if (printlist == null)
                {
                    printlist = new list<string>();
                    localprintserver printserver = new localprintserver();
                    printqueuecollection printqueuesonlocalserver = printserver.getprintqueues(new[] { enumeratedprintqueuetypes.local });
                    foreach (printqueue printer in printqueuesonlocalserver)
                        printlist.add(printer.name);
                }
                return printlist;
            }
        }

        /// <summary>
        /// 执行打印
        /// </summary>
        /// <param name="codesheetmodel">打印的数据</param>
        /// <param name="printname">打印机名称,为空则调用默认的打印机</param>
        public bool run(codesheetmodel outplate, action<exception> execptioncallback, string printname = null)
        {
            execptioncallback = execptioncallback;

            // 检查是否指定了打印机
            if (string.isnullorwhitespace(printname) && printlist.count > 0)
                printname = printlist[0];
            else if (printlist.count <= 0)
            {
                execptioncallback(new exception("未找到可用的打印机"));
                return false;
            }

            if (!printlist.contains(printname))
            {
                execptioncallback(new exception(string.format("未找到打印机 {0}", printname)));
                return false;
            }

            datetime = datetime.now;

            var report = new localreport();
            report.reportpath = "./reports/exitbarreport.rdlc";
            report.datasources.add(new reportdatasource("codesheetdataset", loaddata(outplate)));

            export(report);

            m_currentpageindex = 0;
            print(printname);


            if (m_streams != null)
            {
                foreach (stream stream in m_streams)
                    stream.close();
                m_streams = null;
            }
            deletetempfile();
            return true;
        }

        /// <summary>
        /// 填充要打印的数据
        /// </summary>
        /// <param name="op"></param>
        /// <returns></returns>
        public datatable loaddata(codesheetmodel op)
        {
            datatable dt = new datatable();

            dt.columns.add("codesheetnumber", typeof(string));
            dt.columns.add("contractnuber", typeof(string));
            dt.columns.add("quasisign", typeof(string));
            dt.columns.add("loadingpoint", typeof(string));
            dt.columns.add("deliverystandard", typeof(string));
            dt.columns.add("deliveryaddress", typeof(string));
            dt.columns.add("orderunit", typeof(string));
            dt.columns.add("receivingunit", typeof(string));
            dt.columns.add("settlementunit", typeof(string));
            dt.columns.add("privatelinename", typeof(string));
            dt.columns.add("licensenumber", typeof(string));
            dt.columns.add("billloadno", typeof(string));
            dt.columns.add("shipptype", typeof(string));
            dt.columns.add("deliveryclass", typeof(string));
            dt.columns.add("productdescription", typeof(string));
            dt.columns.add("varietyname", typeof(string));
            dt.columns.add("shipmentno", typeof(string));
            dt.columns.add("brandno", typeof(string));
            dt.columns.add("factoryoutdata", typeof(string));
            dt.columns.add("metermode", typeof(string));
            dt.columns.add("printdatetime", typeof(string));
            //// 产品
            //dt.columns.add("meltingnumber", typeof(string));
            //dt.columns.add("materialscience", typeof(string));
            //dt.columns.add("machiningstate", typeof(string));
            //dt.columns.add("chang", typeof(string));
            //dt.columns.add("netwight", typeof(string));
            //dt.columns.add("bundlenum", typeof(string));
            //dt.columns.add("branchnum", typeof(string));

            datarow dr = dt.newrow();
            dr["codesheetnumber"] = op.codesheetnumber;
            dr["contractnuber"] = op.contractnuber;
            dr["quasisign"] = op.quasisign;
            dr["loadingpoint"] = op.loadingpoint;
            dr["deliverystandard"] = op.deliverystandard;
            dr["deliveryaddress"] = op.deliveryaddress;
            dr["orderunit"] = op.orderunit;
            dr["receivingunit"] = op.receivingunit;
            dr["settlementunit"] = op.settlementunit;
            dr["privatelinename"] = op.privatelinename;
            dr["licensenumber"] = op.licensenumber;
            dr["billloadno"] = op.billloadno;
            dr["shipptype"] = op.shipptype;
            dr["deliveryclass"] = op.deliveryclass;
            dr["productdescription"] = op.productdescription;
            dr["varietyname"] = op.varietyname;
            dr["shipmentno"] = op.shipmentno;
            dr["brandno"] = op.brandno;
            dr["factoryoutdata"] = op.factoryoutdata;
            dr["metermode"] = op.metermode;
            dr["printdatetime"] = op.printdatetime;

            dt.rows.add(dr);
            //// 产品 
            //for (int i = 0; i < productitem.count; i++)
            //{
            //    var model = productitem[i];
            //    var newrow = dt.newrow();
            //    dr["meltingnumber"] = model.meltingnumber;
            //    dr["materialscience"] = model.materialscience;
            //    dr["machiningstate"] = model.machiningstate;
            //    dr["chang"] = model.chang;
            //    dr["netwight"] = model.netwight;
            //    dr["bundlenum"] = model.bundlenum;
            //    dr["branchnum"] = model.branchnum;
            //    dt.rows.add(newrow);
            //}

            return dt;
        }


        /// <summary>
        /// 导出报表的每一个页面到一个emf文件 
        /// </summary>
        /// <param name="report"></param>
        private void export(localreport report)
        {
            string deviceinfo =
                "<deviceinfo>" +
                "  <outputformat>emf</outputformat>" +
                "  <pagewidth>19.30cm</pagewidth>" +
                "  <pageheight>6.68cm</pageheight>" +
                "  <margintop>0.13cm</margintop>" +
                "  <marginleft>1.53cm</marginleft>" +
                "  <marginright>0.13cm</marginright>" +
                "  <marginbottom>0.13cm</marginbottom>" +
                "</deviceinfo>";
            warning[] warnings;
            m_streams = new list<stream>();
            report.render("image", deviceinfo, createstream, out warnings);


            foreach (stream stream in m_streams)
            {
                stream.position = 0;
            }
        }
        /// <summary>
        /// 创建流
        /// </summary>
        /// <param name="name"></param>
        /// <param name="filenameextension"></param>
        /// <param name="encoding"></param>
        /// <param name="mimetype"></param>
        /// <param name="willseek"></param>
        /// <returns></returns>
        private stream createstream(string name,
            string filenameextension, encoding encoding,
            string mimetype, bool willseek)
        {
            //var stream = new filestream(@"./" + name +
            // "." + filenameextension, filemode.create);
            //var stream = new filestream($"./{datetime.tostring("yyyy_mm_dd_hh_mm_ss")}_{name}.{filenameextension}", filemode.create);
            if (!directory.exists("./printfiletemp"))
            {
                directory.createdirectory("./printfiletemp");
            }
            var stream = new filestream(string.format("./printfiletemp/{0}_{1}.{2}", datetime.tostring("yyyy_mm_dd_hh_mm_ss"), name, filenameextension), filemode.create);

            if (m_streams.count < 1)
                m_streams.add(stream);

            return stream;
        }

        /// <summary>
        /// 打印
        /// </summary>
        /// <param name="printername"></param>
        private void print(string printername)
        {
            if (m_streams == null || m_streams.count == 0)
                return;

            printdocument printdoc = new printdocument();
            printdoc.printersettings.printername = printername;
            if (!printdoc.printersettings.isvalid)
            {
                //execptioncallback(new exception($"未找到打印机 {printername}"));
                execptioncallback(new exception(string.format("未找到打印机 {0}", printername)));
                return;
            }


            // 0.001 英寸 = 0.0254 厘米
            //           = 960cm 

            //printdoc.defaultpagesettings.papersize = new papersize("custom", 815, 400);
            printdoc.printersettings.copies = 1;

            printdoc.printpage += new printpageeventhandler(printpage);
            printdoc.print();
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="ev"></param>
        private void printpage(object sender, printpageeventargs ev)
        {
            metafile pageimage = new metafile(m_streams[m_currentpageindex]);
            ev.graphics.drawimage(pageimage, ev.pagebounds);
            ev.hasmorepages = false;
            ev.pagesettings.landscape = true;
        }

        private void deletetempfile()
        {
            dispose();
            foreach (var item in directory.enumeratefiles(appdomain.currentdomain.basedirectory + "printfiletemp"))
            {
                try
                {
                    file.delete(item);
                }
                catch (exception)
                {

                }

            }
        }

        /// <summary>
        /// 释放现有流资源
        /// </summary>
        public void dispose()
        {
            if (m_streams != null)
            {
                foreach (stream stream in m_streams)
                    stream.close();
                m_streams = null;
            }
        }
    }

  

 以上就是三种打印方式。

 以上源码下载地址: