C#编写的Word操作类_有换页_添加表格_文本功能

来源:互联网 发布:mac mini 远程控制 编辑:程序博客网 时间:2024/05/16 15:41
using System;using System.Collections.Generic;using System.Text;using Microsoft.Office.Interop.Word;using Word = Microsoft.Office.Interop.Word;using System.Windows.Forms;using System.Drawing;using System.Runtime.InteropServices;namespace PropertyManagement{    public class ExportWord    {        #region - 属性 -        private static  object oMissing = System.Reflection.Missing.Value;        private static Word._Application oWord = null;        private static Word._Document odoc = null;        private static object Nothing = System.Reflection.Missing.Value;        public enum Orientation        {            横板,            竖板        }        public enum Alignment        {            左对齐,            居中,            右对齐        }        #endregion        #region - 创建新Word -        public static bool CreateWord(bool isVisible)        {            try            {                oWord = new Microsoft.Office.Interop.Word.Application();                //excel.WorkbookBeforeClose += new Microsoft.Office.Interop.Excel.AppEvents_WorkbookBeforeCloseEventHandler(WorkbookBeforeClose);               // ((Word.ApplicationEvents4_Event)oWord).DocumentBeforeClose += new Microsoft.Office.Interop.Word.ApplicationEvents4_DocumentBeforeSaveEventHandler(DocumentBeforeClose);                oWord.Visible = isVisible;                odoc = oWord.Documents.Add(ref oMissing, ref oMissing, ref oMissing, ref oMissing);                return true;            }            catch (Exception ex)            {                MessageBox.Show(ex.Message);                return false;            }        }        public static bool CreateWord()        {            return CreateWord(false);        }        #endregion        #region - 插入表格 -        public static bool InsertTable(System.Data.DataTable dt, bool haveBorder, double[] colWidths)        {            try            {                object Nothing = System.Reflection.Missing.Value;                int lenght = odoc.Characters.Count - 1;                object start = lenght;                object end = lenght;                //表格起始坐标                Microsoft.Office.Interop.Word.Range tableLocation = odoc.Range(ref start, ref end);                //添加Word表格                 Microsoft.Office.Interop.Word.Table table = odoc.Tables.Add(tableLocation, dt.Rows.Count, dt.Columns.Count, ref Nothing, ref Nothing);                if (colWidths != null)                {                    for (int i = 0; i < colWidths.Length; i++)                    {                        table.Columns[i + 1].Width = (float)(28.5F * colWidths[i]);                    }                }                ///设置TABLE的样式                table.Rows.HeightRule = Microsoft.Office.Interop.Word.WdRowHeightRule.wdRowHeightAtLeast;                table.Rows.Height = oWord.CentimetersToPoints(float.Parse("0.8"));                table.Range.Font.Size = 10.5F;                table.Range.Font.Name = "宋体";                table.Range.Font.Bold = 0;                table.Range.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter;                table.Range.Cells.VerticalAlignment = Microsoft.Office.Interop.Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter;                if (haveBorder == true)                {                    //设置外框样式                    table.Borders.OutsideLineStyle = Microsoft.Office.Interop.Word.WdLineStyle.wdLineStyleSingle;                    table.Borders.InsideLineStyle = Microsoft.Office.Interop.Word.WdLineStyle.wdLineStyleSingle;                    //样式设置结束                }                for (int row = 0; row < dt.Rows.Count; row++)                {                    for (int col = 0; col < dt.Columns.Count; col++)                    {                        table.Cell(row + 1, col + 1).Range.Text = dt.Rows[row][col].ToString();                    }                }                return true;            }            catch (Exception e)            {                MessageBox.Show(e.ToString(), "错误提示", MessageBoxButtons.OK, MessageBoxIcon.Error);                return false;            }            finally            {            }        }        public static bool InsertTable(System.Data.DataTable dt, bool haveBorder)        {            return InsertTable(dt, haveBorder, null);        }        public static bool InsertTable(System.Data.DataTable dt)        {            return InsertTable(dt, false, null);        }        #endregion        #region - 插入文本 -        public static bool InsertText(string strText, System.Drawing.Font font, Alignment alignment, bool isAftre)        {            try            {                Word.Range rng = odoc.Content;                int lenght = odoc.Characters.Count - 1;                object start = lenght;                object end = lenght;                rng = odoc.Range(ref start, ref end);                if (isAftre == true)                {                    strText += "\r\n";                }                rng.Text = strText;                rng.Font.Name = font.Name;                rng.Font.Size = font.Size;                if (font.Style == FontStyle.Bold) { rng.Font.Bold = 1; } //设置单元格中字体为粗体                SetAlignment(rng, alignment);                return true;            }            catch (Exception)            {                return false;            }        }        public static bool InsertText(string strText)        {            return InsertText(strText, new System.Drawing.Font("宋体", 10.5F, FontStyle.Bold), Alignment.左对齐, false);        }        #endregion        #region - 设置对齐方式 -        private static Microsoft.Office.Interop.Word.WdParagraphAlignment SetAlignment(Range rng, Alignment alignment)        {            rng.ParagraphFormat.Alignment = SetAlignment(alignment);            return SetAlignment(alignment);        }        private static Microsoft.Office.Interop.Word.WdParagraphAlignment SetAlignment(Alignment alignment)        {            if (alignment == Alignment.居中)            {                return Word.WdParagraphAlignment.wdAlignParagraphCenter;            }            else if (alignment == Alignment.左对齐)            {                return Word.WdParagraphAlignment.wdAlignParagraphLeft;            }            else            { return Word.WdParagraphAlignment.wdAlignParagraphRight; }        }        #endregion        #region - 页面设置 -        public static void SetPage(Orientation orientation, double width, double height, double topMargin, double leftMargin, double rightMargin, double bottomMargin)        {            odoc.PageSetup.PageWidth = oWord.CentimetersToPoints((float)width);            odoc.PageSetup.PageHeight = oWord.CentimetersToPoints((float)height);            if (orientation == Orientation.横板)            {                odoc.PageSetup.Orientation = Microsoft.Office.Interop.Word.WdOrientation.wdOrientLandscape;            }            odoc.PageSetup.TopMargin = (float)(topMargin * 25);//上边距             odoc.PageSetup.LeftMargin = (float)(leftMargin * 25);//左边距             odoc.PageSetup.RightMargin = (float)(rightMargin * 25);//右边距             odoc.PageSetup.BottomMargin = (float)(bottomMargin * 25);//下边距        }        public static void SetPage(Orientation orientation, double topMargin, double leftMargin, double rightMargin, double bottomMargin)        {            SetPage(orientation, 21, 29.7, topMargin, leftMargin, rightMargin, bottomMargin);        }        public static void SetPage(double topMargin, double leftMargin, double rightMargin, double bottomMargin)        {            SetPage(Orientation.竖板, 21, 29.7, topMargin, leftMargin, rightMargin, bottomMargin);        }        #endregion        #region - 插入分页符 -        public static void InsertBreak()        {            Word.Paragraph para;            para = odoc.Content.Paragraphs.Add(ref Nothing);            object pBreak = (int)Word.WdBreakType.wdPageBreak;            para.Range.InsertBreak(ref pBreak);        }        #endregion        #region - 关闭当前文档 -        public static bool CloseDocument()        {            try            {                if (odoc != null)                {                    Marshal.ReleaseComObject(odoc);                    odoc = null;                }                oWord.Quit(ref Nothing, ref Nothing, ref Nothing);                return true;            }            catch (Exception)            {                return false;            }        }        #endregion        #region - 关闭程序 -        public static bool Quit()        {            try            {                object saveOption = Word.WdSaveOptions.wdDoNotSaveChanges;                oWord.Quit(ref saveOption, ref Nothing, ref Nothing);                return true;            }            catch (Exception)            {                return false;            }        }        #endregion        #region - 保存文档 -        public static bool Save(string savePath, bool isClose)        {            try            {                object fileName = savePath;                odoc.SaveAs(ref fileName);                if (isClose)                {                    return CloseDocument();                }                return true;            }            catch (Exception)            {                return false;            }        }        public static void Save()        {            try            {                oWord.Visible = true;                odoc.SaveAs();            }            catch (Exception)            {                MessageBox.Show( "程序出错,请重新运行!", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);                            }        }        #endregion        #region - 插入页脚 -        public static bool InsertPageFooter(string text, System.Drawing.Font font, Alignment alignment)        {            try            {                oWord.ActiveWindow.View.SeekView = Word.WdSeekView.wdSeekCurrentPageFooter;//页脚                 oWord.Selection.InsertAfter(text);                GetWordFont(oWord.Selection.Font, font);                SetAlignment(oWord.Selection.Range, alignment);                return true;            }            catch (Exception)            {                return false;            }        }        public static bool InsertPageFooterNumber(System.Drawing.Font font, Alignment alignment)        {            try            {                oWord.ActiveWindow.View.SeekView = WdSeekView.wdSeekCurrentPageHeader;                oWord.Selection.WholeStory();                oWord.Selection.ParagraphFormat.Borders[WdBorderType.wdBorderBottom].LineStyle = WdLineStyle.wdLineStyleNone;                oWord.ActiveWindow.View.SeekView = Word.WdSeekView.wdSeekMainDocument;                oWord.ActiveWindow.View.SeekView = Word.WdSeekView.wdSeekCurrentPageFooter;//页脚                 oWord.Selection.TypeText("第");                object page = WdFieldType.wdFieldPage;                oWord.Selection.Fields.Add(oWord.Selection.Range, ref page, ref Nothing, ref Nothing);                oWord.Selection.TypeText("页/共");                object pages = WdFieldType.wdFieldNumPages;                oWord.Selection.Fields.Add(oWord.Selection.Range, ref pages, ref Nothing, ref Nothing);                oWord.Selection.TypeText("页");                GetWordFont(oWord.Selection.Font, font);                SetAlignment(oWord.Selection.Range, alignment);                oWord.ActiveWindow.View.SeekView = Word.WdSeekView.wdSeekMainDocument;                return true;            }            catch (Exception)            {                return false;            }        }        #endregion        #region - 字体格式设定 -        public static void GetWordFont(Microsoft.Office.Interop.Word.Font wordFont, System.Drawing.Font font)        {            wordFont.Name = font.Name;            wordFont.Size = font.Size;            if (font.Bold) { wordFont.Bold = 1; }            if (font.Italic) { wordFont.Italic = 1; }            if (font.Underline == true)            {                wordFont.Underline = Microsoft.Office.Interop.Word.WdUnderline.wdUnderlineNone;            }            wordFont.UnderlineColor = Microsoft.Office.Interop.Word.WdColor.wdColorAutomatic;            if (font.Strikeout)            {                wordFont.StrikeThrough = 1;//删除线            }        }        #endregion        #region - 获取Word中的颜色 -        public static WdColor GetWordColor(Color c)        {            UInt32 R = 0x1, G = 0x100, B = 0x10000;            return (Microsoft.Office.Interop.Word.WdColor)(R * c.R + G * c.G + B * c.B);        }        #endregion        public static void DocumentBeforeClose()        {            //KillProcess.KillSpecialExcel(oWord);            CloseDocument();        }    }}

举例:


 private void wordTMSI_Click(object sender, EventArgs e)        {            flag = false;            flag1 = false;            Details details = new Details();            details.ShowDialog();            if (flag)            {                if (ExportWord.CreateWord() == false)                {                    MessageBox.Show("文件创造失败.", "错误提示", MessageBoxButtons.OK, MessageBoxIcon.Error);                    return;                }                int rows = dt.Rows.Count;                for (int i = 0; i < rows; i++)                {                    ExportWord.InsertText("物业管理费收费凭证", new Font("微软雅黑", 14, FontStyle.Bold), ExportWord.Alignment.居中, true);                    string strHouse = dt.Rows[i][0].ToString() + " 小区  " + dt.Rows[i][2].ToString() + " 幢 " + dt.Rows[i][4].ToString() + " 室   " + dt.Rows[i][5].ToString() + "   同志你好!";                    string strTime = "以下是你户    " + year.ToString() + " 年  " + "   应缴物业管理费   情况:";                    ExportWord.InsertText(strHouse, new Font("宋体", 12, FontStyle.Regular), ExportWord.Alignment.居中, true);                    ExportWord.InsertText(strTime, new Font("宋体", 12, FontStyle.Regular), ExportWord.Alignment.居中, true);                    DataTable storedt = new DataTable();                    double[] columnWidths = { 2.5, 4, 2, 2, 2.5, 2.5 };                    storedt.Columns.Add("Area");                    storedt.Columns.Add("Standard");                    storedt.Columns.Add("Mouth_Charge");                    storedt.Columns.Add("Mouths");                    storedt.Columns.Add("Finance_Charge");                    storedt.Columns.Add("Issued_Charge");                    storedt.Rows.Add("建筑面积", "收费标准", "月缴费", "收缴月份", "应缴金额", "实缴金额");                    double finance = 0.0;                    double area = 0.00;                    string str = dt.Rows[i][6].ToString();                    if (!String.IsNullOrEmpty(str))                    {                        area = Convert.ToDouble(dt.Rows[i][6].ToString());                    }                    string strStandard = cStandard + " 元/平方米/月";                    string strCMouth = Math.Round((area * cStandard), 2).ToString();                    string strMonths = startM + "-" + endM;                    string strF = Math.Round(area * cStandard * (endM - startM + 1), 2).ToString();                    finance += Math.Round(area * cStandard * (endM - startM + 1), 2);                    string strI = " ";                    storedt.Rows.Add(area.ToString(), strStandard, strCMouth, strMonths, strF, strI);                    if (flag1)                    {                        string strStandard1 = cStandard1 + " 元/平方米/月";                        string strCMouth1 = Math.Round((area * cStandard1), 2).ToString();                        string strMonths1 = startM1 + "-" + endM1;                        string strF1 = Math.Round(area * cStandard1 * (endM1 - startM1 + 1), 2).ToString();                        finance += Math.Round(area * cStandard1 * (endM1 - startM1 + 1), 2);                        string strI1 = " ";                        storedt.Rows.Add(area.ToString(), strStandard1, strCMouth1, strMonths1, strF1, strI1);                        storedt.Rows.Add("合计:", "", "", "", finance, "");                    }                    ExportWord.InsertTable(storedt, true, columnWidths);                    ExportWord.InsertText("新世纪物业管理有限公司", new Font("宋体", 12, FontStyle.Regular), ExportWord.Alignment.右对齐, true);                    ExportWord.InsertText(DateTime.Now.ToString("D"), new Font("宋体", 12, FontStyle.Regular), ExportWord.Alignment.右对齐, true);                    if ((i + 1) % 3 != 0 && flag1)                    {                        ExportWord.InsertText("", new Font("宋体", 12, FontStyle.Regular), ExportWord.Alignment.右对齐, true);                        ExportWord.InsertText("", new Font("宋体", 12, FontStyle.Regular), ExportWord.Alignment.右对齐, true);                        ExportWord.InsertText("", new Font("宋体", 12, FontStyle.Regular), ExportWord.Alignment.右对齐, true);                        ExportWord.InsertText("", new Font("宋体", 12, FontStyle.Regular), ExportWord.Alignment.右对齐, true);                    }                    if ((i + 1) % 3 != 0 && !flag1)                    {                        ExportWord.InsertText("", new Font("宋体", 12, FontStyle.Regular), ExportWord.Alignment.右对齐, true);                        ExportWord.InsertText("", new Font("宋体", 12, FontStyle.Regular), ExportWord.Alignment.右对齐, true);                        ExportWord.InsertText("", new Font("宋体", 12, FontStyle.Regular), ExportWord.Alignment.右对齐, true);                        ExportWord.InsertText("", new Font("宋体", 12, FontStyle.Regular), ExportWord.Alignment.右对齐, true);                        ExportWord.InsertText("", new Font("宋体", 12, FontStyle.Regular), ExportWord.Alignment.右对齐, true);                        ExportWord.InsertText("", new Font("宋体", 12, FontStyle.Regular), ExportWord.Alignment.右对齐, true);                    }                    if ((i + 1) % 3 == 0)                    {                        ExportWord.InsertBreak();                    }                }                ExportWord.SetPage(ExportWord.Orientation.竖板, 21, 29.7, 2.54, 3.18, 3.18, 2.54);                ExportWord.Save();            }            else            {                MessageBox.Show(this, "请选择要收取的月份以及收费标准!", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);            }        }