C# 三種列印方式含代碼

来源:https://www.cnblogs.com/wendj/archive/2019/04/18/10728685.html
-Advertisement-
Play Games

一:C#代碼直接列印pdf文件(列印質保書pdf文件) 引用: 代碼註釋很詳細了。 二:先生成excel在調用列印(生成excel主要在於佈局) 按鈕事件代碼: PrintHelper.cs文件代碼 生成的excel預覽 三 在Visual Studio中通過插件編輯rdlc文件進行可視化佈局(動態 ...


 

 

 

 

 

一:C#代碼直接列印pdf文件(列印質保書pdf文件)

引用:

 

代碼註釋很詳細了。

        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預覽

 

三 在Visual Studio中通過插件編輯rdlc文件進行可視化佈局(動態添加行的我暫時沒有弄出來,這裡只演示固定欄位的列印)

 首先引用:

 

第一步:安裝插件 

搜索rdlc

 

 第二步:這裡下載好之後從新啟動vs它會自動安裝插件。安裝好後創建文件。

 

 

 

 

 第三步:可視化佈局操作

 

 

 第四步:設置數據綁定,在需要綁定數據的單元格中滑鼠右鍵點擊文本框屬性。

 

 

名稱:與實體屬性寫法一致  值:[與實體屬性寫法一致]

 

設置字體及大小

 

 

 第五步:佈局及所有欄位寫好之後就設置數據集(我這裡用的是本地實體模型)

右鍵添加數據集

 

這裡選擇你要綁定的實體

 

 

 

 

註意:當界面設計好之後我們重新生成項目總是提示生成失敗,而vs也不提示哪裡出錯了。

我就猜測是不是這個rdlc文件的問題,我就試著把rdlc文件排除在項目外,再次生成就可以了。

當然這個不影響我們編輯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;
            }
        }
    }

  

 以上就是三種列印方式。

 以上源碼下載地址:https://download.csdn.net/download/qingchundaima/11125329


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 一般的介面實現多態 定義介面 定義實現的類 一般實現的方法 升級版 添加自定義(這個網上好多) 實現類 調用方法 這個可以避免需要維護swich語句 ...
  • 預設輸入軸: Horizontal 和 Vertical被映射到w, a, s, d鍵和方向鍵 Fire1, Fire2, Fire3被分別映射到Ctrl,Option(Alt)和Command鍵 Mouse X 和 Mouse Y被映射到滑鼠移動增量 Window Shake X 和 Window ...
  • 從伺服器下載datatable到本地,有多種處理方式,下麵介紹三種。 方式一,將datatable轉為txt下載。 步驟: 1.將datatable內容下載到伺服器txt中 2.將伺服器的txt下載到本地來 3.刪除伺服器上的txt 方式二,datatable綁定到控制項GridView後下載 步驟: ...
  • 今天發現有些郵件無法讀取Attachments,郵件明明有附件,但使用Mailkit讀取時,Attachments為空,我用的IMAP協議讀取收件箱里的郵件,處理完後移動已刪除: 附件是一個Excel文件,死活出不來。詢問用戶怎麼發的附件,說是通過WPS發的 解決方法: 換Pop3Client,就讀 ...
  • .net core相比之前.net的是一個可以跨平臺,脫離iis運行的語言,並且項目啟動的效率要比用iis啟動快,可以說進一步提高了開發的效率。要想自己的項目core脫離iis,首先選擇vs啟動項目的載體: 如下圖,不要選擇IIS Express 選擇好後再啟動項目,會出現一個cmd視窗,我的理解這 ...
  • 一.概述 在上篇中,探討了互動式用戶身份驗證,使用的是OIDC協議。 在之前篇中對API訪問使用的是OAuth2.0協議。這篇把這兩個部分放在一起,OpenID Connect和OAuth 2.0組合的優點在於:可以使用單個協議和令牌服務,進行單次交換來實現這兩者。 上篇中使用了OpenID Con ...
  • 重點:通過二級制流序列化和反序列化的對象呢,屬性值並不會丟失!!! 而通過JsonConvert進行的string類型的序列化反序列化,多餘的屬性值會丟失!!! 就是真麽神奇! ...
  • //根據Url地址得到網頁的html源碼 public static string GetWebContent(string Url) { string strResult = ""; try { HttpWebRequest request = (HttpWebRequest)WebRequest ...
一周排行
    -Advertisement-
    Play Games
  • 移動開發(一):使用.NET MAUI開發第一個安卓APP 對於工作多年的C#程式員來說,近來想嘗試開發一款安卓APP,考慮了很久最終選擇使用.NET MAUI這個微軟官方的框架來嘗試體驗開發安卓APP,畢竟是使用Visual Studio開發工具,使用起來也比較的順手,結合微軟官方的教程進行了安卓 ...
  • 前言 QuestPDF 是一個開源 .NET 庫,用於生成 PDF 文檔。使用了C# Fluent API方式可簡化開發、減少錯誤並提高工作效率。利用它可以輕鬆生成 PDF 報告、發票、導出文件等。 項目介紹 QuestPDF 是一個革命性的開源 .NET 庫,它徹底改變了我們生成 PDF 文檔的方 ...
  • 項目地址 項目後端地址: https://github.com/ZyPLJ/ZYTteeHole 項目前端頁面地址: ZyPLJ/TreeHoleVue (github.com) https://github.com/ZyPLJ/TreeHoleVue 目前項目測試訪問地址: http://tree ...
  • 話不多說,直接開乾 一.下載 1.官方鏈接下載: https://www.microsoft.com/zh-cn/sql-server/sql-server-downloads 2.在下載目錄中找到下麵這個小的安裝包 SQL2022-SSEI-Dev.exe,運行開始下載SQL server; 二. ...
  • 前言 隨著物聯網(IoT)技術的迅猛發展,MQTT(消息隊列遙測傳輸)協議憑藉其輕量級和高效性,已成為眾多物聯網應用的首選通信標準。 MQTTnet 作為一個高性能的 .NET 開源庫,為 .NET 平臺上的 MQTT 客戶端與伺服器開發提供了強大的支持。 本文將全面介紹 MQTTnet 的核心功能 ...
  • Serilog支持多種接收器用於日誌存儲,增強器用於添加屬性,LogContext管理動態屬性,支持多種輸出格式包括純文本、JSON及ExpressionTemplate。還提供了自定義格式化選項,適用於不同需求。 ...
  • 目錄簡介獲取 HTML 文檔解析 HTML 文檔測試參考文章 簡介 動態內容網站使用 JavaScript 腳本動態檢索和渲染數據,爬取信息時需要模擬瀏覽器行為,否則獲取到的源碼基本是空的。 本文使用的爬取步驟如下: 使用 Selenium 獲取渲染後的 HTML 文檔 使用 HtmlAgility ...
  • 1.前言 什麼是熱更新 游戲或者軟體更新時,無需重新下載客戶端進行安裝,而是在應用程式啟動的情況下,在內部進行資源或者代碼更新 Unity目前常用熱更新解決方案 HybridCLR,Xlua,ILRuntime等 Unity目前常用資源管理解決方案 AssetBundles,Addressable, ...
  • 本文章主要是在C# ASP.NET Core Web API框架實現向手機發送驗證碼簡訊功能。這裡我選擇是一個互億無線簡訊驗證碼平臺,其實像阿裡雲,騰訊雲上面也可以。 首先我們先去 互億無線 https://www.ihuyi.com/api/sms.html 去註冊一個賬號 註冊完成賬號後,它會送 ...
  • 通過以下方式可以高效,並保證數據同步的可靠性 1.API設計 使用RESTful設計,確保API端點明確,並使用適當的HTTP方法(如POST用於創建,PUT用於更新)。 設計清晰的請求和響應模型,以確保客戶端能夠理解預期格式。 2.數據驗證 在伺服器端進行嚴格的數據驗證,確保接收到的數據符合預期格 ...