Barcode 导入Word

最近搞了几天barcord,把barcode导入word文档里,费了不少力气才搞好。

在此记下,以防以后会用到。

这个东东在网上还真难找到相关的资料。


首先在页面上写个html和js(用来选中和取消选中)。

 <div><asp:CheckBoxList ID="cblBarcodeList" runat="server" RepeatColumns ="4" Width="99.9%"></asp:CheckBoxList></div>

    <script type="text/javascript">
        $(document).ready(function () {
            $("#btnSelectAll").click(function () {
                CheckedAllBarcode();
            });

            $("#btnClearAll").click(function () {
                UncheckedAllBarcode();
            });
        });

        function CheckedAllBarcode() {
            $("input[type=checkbox]").each(function (i, val) {
                $(this).attr("checked", true);
                });
        }

        function UncheckedAllBarcode() {
            $("input[type=checkbox]").each(function (i, val) {
                $(this).attr("checked", false);
            });
        }
    </script>


其次.cs代码导出barcode.

 protected void btnExport_Click(object sender, EventArgs e)
        {
            List<string> barcodeValues = new List<string>();
            foreach (ListItem item in this.cblBarcodeList.Items)
            {
                if (item.Selected)
                {
                    barcodeValues.Add(item.Text+";"+item.Value);
                }
            }

            ImportBarcode(barcodeValues);
        }



 private void ImportBarcode(List<string> barcodeList)
        {
            //calculate PageNumber by barcodeValues length.
            int barcodeCount = barcodeList.Count;
            const float itemsInPage = 10;
            float dPageCount = barcodeCount / itemsInPage;
            int pageCount = Convert.ToInt32(System.Math.Ceiling(dPageCount));

            //"\\endofdoc" is a predefined bookmark, must be this format;
            object oEndOfDoc = "\\endofdoc";
            object oMissing = System.Reflection.Missing.Value;

            try
            {
                //create word document
                Word._Application oWord = new Word.Application();
                Word._Document oDoc = oWord.Documents.Add(ref oMissing, ref oMissing, ref oMissing, ref oMissing);
                oWord.Visible = true;
                SetWordApp(oWord);

                #region create all Pages
                //create each Page and Import Barcode
                for (int p = 0; p < pageCount; p++)
                {
                    #region create Page

                    //insert title at first paragraph //oPara1.Range.Font.Bold = 1;
                    Word.Paragraph oParaFirst;
                    oParaFirst = oDoc.Content.Paragraphs.Add(ref oMissing);
                    oParaFirst.Range.Text = "";
                    oParaFirst.Range.Font.Size = 9f;
                    oParaFirst.Format.SpaceAfter = 8;
                    oParaFirst.Range.InsertParagraphAfter();

                    #endregion

                    #region create oTable and Row height, width;

                    //create table=row5*columns2;
                    Word.Table oTable;
                    Word.Range wrdRng = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range;
                    oTable = oDoc.Tables.Add(wrdRng, 10, 2, ref oMissing, ref oMissing);
                    oTable.Range.ParagraphFormat.SpaceAfter = 0;

                    //set row height
                    for (int i = 1; i <= oTable.Range.Rows.Count; i++)
                    {
                        //height: 132=4.66cm;//barcode row height
                        if (i % 2 != 0)
                        {
                            oTable.Range.Rows[i].Height = 55;
                        }
                        else
                        {
                            oTable.Range.Rows[i].Height = 86;
                        }
                    }

                    //set columns width;
                    for (int c = 1; c < oTable.Columns.Count; c++)
                    {
                        //can be use oWord.InchesToPoints(2) to set value; 236 point=8.33cm;
                        oTable.Columns[c].Width = 243.7f;
                    }

                    #endregion

                    #region print each Barcode

                    string barcodeStrings = string.Empty;
                    string barcodeValues = string.Empty;

                    int forCount = 0;
                    if (barcodeCount >= (p + 1) * 10)
                    {
                        forCount = (p + 1) * 10;
                    }
                    else
                    {
                        forCount = barcodeCount;
                    }
                    for (int i = p * 10; i < forCount; i++)
                    {
                        barcodeStrings = barcodeList[i].Split(';')[0];
                        barcodeValues = barcodeList[i].Split(';')[1];
                        ImportBarcodeToWord(barcodeStrings, barcodeValues, 6, oTable, oDoc, i);
                    }

                    #endregion
                }

                #endregion

                #region save document as .doc extention since barcode width and height will be changed when reopend

                string fileName = SaveWord(oDoc);
                oDoc.Close();
                oWord.Application.Quit(ref oMissing, ref oMissing, ref oMissing);
                oDoc = null;
                oWord = null;
                Response.Redirect(fileName);

                #endregion
            }
            catch (Exception ex)
            {
                this.lblBarCodeMessage.Text = ex.Message;
            }
        }

        /// <summary>
        /// import barcode information and value into the word tables.
        /// </summary>
        /// <param name="barcodeText"></param>
        /// <param name="barcodeValues"></param>
        /// <param name="type"></param>
        /// <param name="oTable"></param>
        /// <param name="oDoc"></param>
        private void ImportBarcodeToWord(string barcodeText, string barcodeValues, int type, Word.Table oTable, Word._Document oDoc, int index)
        {
            #region create Row height, width and set each Cell value;

            int pageItemsMode = 10;
            int itemMode=index % pageItemsMode;

            int[] barcodeValuesRowIndex = new int[10] {2, 2, 4, 4, 6, 6, 8, 8, 10, 10 };
            int[] barcodeTextRowIndex = new int[10] { 1, 1, 3, 3, 5, 5, 7, 7 , 9, 9};
            int[] barcodeColIndex = new int[10] { 1, 2, 1, 2, 1, 2, 1, 2, 1, 2 };

            int rValue = barcodeValuesRowIndex[itemMode];
            int rText = barcodeTextRowIndex[itemMode];
            int c = barcodeColIndex[itemMode];

            oTable.Cell(rValue, c).Range.Select();
            WriteBarcode(oDoc, barcodeText);

            oTable.Cell(rText, c).Range.Text = WriteBarcodeInfo(barcodeValues);

            #endregion
        }

        /// <summary>
        /// format barcode header infomation.
        /// </summary>
        /// <param name="barcodeText">barcode display text</param>
        /// <param name="barcodeValues">array of barcode header values</param>
        /// <returns>formated strings</returns>
        private string WriteBarcodeInfo(string barcodeValues)
        {
            //get diseaseNo, department name and equipment name;
            string[] barcodeValue = barcodeValues.Split(',');
            string resultString = string.Format("Content1. {0}\r\nContent2{1}\r\nConten3t {2}", barcodeValue[0], barcodeValue[1], barcodeValue[2]);

            return resultString;
        }

        /// <summary>
        ///
        /// </summary>
        /// <param name="doc"></param>
        /// <param name="barcodeText"></param>
        private void WriteBarcode(Word._Document doc, string barcodeText)
        {
            #region one way
            object mvalue = System.Reflection.Missing.Value;
            object obj1 = "BARCODE.BarCodeCtrl.1";

            doc.ActiveWindow.ActivePane.View.SeekView = Microsoft.Office.Interop.Word.WdSeekView.wdSeekMainDocument;
            object oleControl = doc.ActiveWindow.Selection.InlineShapes.AddOLEControl(ref obj1, ref mvalue).OLEFormat.Object;

            ((BARCODELib.IBarCodeCtrl)oleControl).Style = 6;
            ((BARCODELib.IBarCodeCtrl)oleControl).Value = string.Format("*{0}*", barcodeText);

            doc.ActiveWindow.Selection.InlineShapes[1].Width = 205f;
            doc.ActiveWindow.Selection.InlineShapes[1].Height = 50f;
            doc.ActiveWindow.Selection.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter;
            #endregion
        }

        /// <summary>
        /// Set table sytle.
        /// </summary>
        /// <param name="oTable"></param>
        private void SetTableStyle(Word.Table oTable)
        {
            #region set table style format
            //header 12.5mm=35;
            oTable.Borders.OutsideColor = Word.WdColor.wdColorAutomatic;
            oTable.Borders.OutsideColorIndex = Word.WdColorIndex.wdAuto;
            oTable.Borders.OutsideLineStyle = Word.WdLineStyle.wdLineStyleSingle;
            oTable.Borders.OutsideLineWidth = Word.WdLineWidth.wdLineWidth050pt;

            oTable.Borders.InsideColor = Word.WdColor.wdColorAutomatic;
            oTable.Borders.InsideColorIndex = Word.WdColorIndex.wdAuto;
            oTable.Borders.InsideLineStyle = Word.WdLineStyle.wdLineStyleSingle;
            oTable.Borders.InsideLineWidth = Word.WdLineWidth.wdLineWidth050pt;

            oTable.Rows[1].Range.Font.Bold = 0;
            oTable.Rows[1].Range.Font.Italic = 1;
            #endregion
        }

        private void SetWordApp(Word._Application WApp)
        {
            WApp.ActiveDocument.PageSetup.Orientation = Microsoft.Office.Interop.Word.WdOrientation.wdOrientPortrait;
            WApp.ActiveDocument.PageSetup.TopMargin = WApp.CentimetersToPoints(1.25f);
            WApp.ActiveDocument.PageSetup.BottomMargin = WApp.CentimetersToPoints(2.54f);
            WApp.ActiveDocument.PageSetup.LeftMargin = WApp.CentimetersToPoints(1.9f);
            WApp.ActiveDocument.PageSetup.RightMargin = WApp.CentimetersToPoints(1.9f);
            WApp.ActiveDocument.PageSetup.Gutter = WApp.CentimetersToPoints(0f);//装订线位置
            WApp.ActiveDocument.PageSetup.HeaderDistance = WApp.CentimetersToPoints(1.5f);//页眉
            WApp.ActiveDocument.PageSetup.FooterDistance = WApp.CentimetersToPoints(1.75f);//页脚
            WApp.ActiveDocument.PageSetup.PageWidth = WApp.CentimetersToPoints(21f);//纸张宽度
            WApp.ActiveDocument.PageSetup.PageHeight = WApp.CentimetersToPoints(29.7f);//纸张高度
        }

        public string SaveWord(Word._Document doc)
        {
            string downloadPath = Server.MapPath("~\\DownloadWord");
            string yearAndMonth=DateTime.Now.ToString("yyyyMM");
            string subfilePath = string.Format("{0}\\{1}", downloadPath, yearAndMonth);
            string savedfileName = DateTime.Now.ToFileTimeUtc().ToString();

            object myNothing = System.Reflection.Missing.Value;
            object myFileName =string.Format("{0}\\{1}",subfilePath, savedfileName);
            object myWordFormatDocument = Word.WdSaveFormat.wdFormatDocument;

            if (!System.IO.Directory.Exists(subfilePath))
            {
                System.IO.Directory.CreateDirectory(subfilePath);
            }

            try
            {
                doc.SaveAs(ref myFileName, ref myWordFormatDocument, ref myNothing, ref myNothing, ref myNothing, ref myNothing,
                    ref myNothing, ref myNothing, ref myNothing, ref myNothing, ref myNothing, ref myNothing, ref myNothing,
                    ref myNothing, ref myNothing, ref myNothing);
            }
            catch
            {
                throw new Exception("Happened error! Save Word File Unsuccessfully.");
            }

            return string.Format("/DownloadWord/{0}/{1}.doc", yearAndMonth, savedfileName);
        }  

最后注意导入命名空间:

using BARCODELib;
using Word = Microsoft.Office.Interop.Word;

加入相关的dll 和barcode Com组件。


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值