<----my github

使用com组件操作word和excel

​ com组件对于我来说一直很谜,尤其是操作word和excel部分,今天在这好好整理一下用到的知识。

本次使用的语言是c#,代码仅供参考。

一、操作word

首先添加对这个com组件的引用:

using MsWord = Microsoft.Office.Interop.Word;

然后通过演示添加章节的部分来说明使用方法,注释部分基本都有说明:

//添加章节
        public void addChapter(object sender, RoutedEventArgs e)
        {
            MsWord.Range cur_Range;  //当前选择部分
            int current_section = 1;	

            String docFileName = Directory.GetCurrentDirectory() + @"\abc.doc";
            //应用和文档及缺省值

            oWord = new MsWord.Application();	//word应用
            object missing = System.Reflection.Missing.Value;	//缺省值,供后面使用
            oDoc = oWord.Documents.Add(ref missing, ref missing, ref missing, ref missing);		//word应用打开一个文档,这个文档为oDoc
            oDoc.Activate();

            object section_next_page = MsWord.WdBreakType.wdSectionBreakNextPage;	//选择下一页,用于添加章节
            object page_break = MsWord.WdBreakType.wdPageBreak;

            //选中第一章第一段
            current_section = oDoc.Sections.Count;
            current_section++;	//section从已有的加1
            oDoc.Sections.Add();	//添加一个section
            oDoc.Sections[current_section].Range.Paragraphs[1].Range.Select();//选择
            cur_Range = oDoc.Sections[current_section].Range.Paragraphs[1].Range;
            cur_Range.Select();	//选择

            object wd_FontSize_Index;
            wd_FontSize_Index = 14; //`1级标题
            oWord.ActiveDocument.Styles.get_Item(ref wd_FontSize_Index).ParagraphFormat.Alignment = MsWord.WdParagraphAlignment.wdAlignParagraphCenter;
            oWord.ActiveDocument.Styles.get_Item(ref wd_FontSize_Index).Font.Name = "微软雅黑";
            oWord.ActiveDocument.Styles.get_Item(ref wd_FontSize_Index).Font.Size = 20;
            object title_style = MsWord.WdBuiltinStyle.wdStyleHeading1; //标题样式
            oDoc.Sections[current_section].Range.Select();
            MsWord.Selection currentSelection = oWord.Selection;
            currentSelection = oWord.Selection;
            //读取文本框数据
            String str = "";
            byte[] textData = Encoding.UTF8.GetBytes(wordContent.Text);//wordContent是一个文本框,只要知道他的Text属性是文字就好
            MemoryStream stream = new MemoryStream(textData);
            StreamReader sr = new StreamReader(stream);
            //写入标题
            str = sr.ReadLine();
            currentSelection.TypeText(str);
            currentSelection.TypeParagraph(); //段落标记
            str = sr.ReadLine();//正文
            while (str != null)
            {
                currentSelection.TypeText(str);
                currentSelection.TypeParagraph(); 
                str = sr.ReadLine();
            }

            //结束读取流
            sr.Close();
            stream.Close();
            //设置标题格式
            cur_Range = oDoc.Sections[current_section].Range.Paragraphs[1].Range;
            cur_Range.set_Style(ref title_style);
            oDoc.Sections[current_section].Range.Paragraphs[1].Alignment =
            MsWord.WdParagraphAlignment.wdAlignParagraphCenter;
            //关闭并保存文件
            object fileName = docFileName;
            oDoc.SaveAs2(ref fileName);
            oDoc.Close();
        }

至于其他的操作和上面大体类似,这里只做部分说明:

1.添加参考文献

  1. 声明变量,打开word、添加缺省值、打开文档、选中现在的部分
  2. 获取文本框中的文字
  3. 添加一个小节
  4. 小节中添加“参考文献”四个字,并在第六步设置字体属性
  5. 将文本框中的文字按行提取出来,加上数字前缀加入到小节中
  6. 设置文字的字体属性
  7. 关闭、保存文件,释放资源

2.添加艺术字

添加艺术字比较麻烦,这里做一下演示:

​ oDoc.Shapes.AddTextEffect(Microsoft.Office.Core.MsoPresetTextEffect.msoTextEffect29, str,
​ "微软雅黑", 24, Microsoft.Office.Core.MsoTriState.msoFalse, Microsoft.Office.Core.MsoTriState.msoFalse,
​ leftPosition, toptPosition);这句是最重要的

 //添加艺术字
        public void addArtCharactere(object sender, RoutedEventArgs e)
        {
            /*
            	这里省略了打开文档的操作,和上面的添加章节的部分是完全一致的
            */
            object page_break = MsWord.WdBreakType.wdPageBreak;

            //从textbox中获取摘要
            String str = "";
            //添加一个小节
            current_section = oDoc.Sections.Count;
            current_section++;
            oDoc.Sections.Add();
            oDoc.Sections[current_section].Range.Paragraphs[1].Range.Select();
            cur_Range = oDoc.Sections[current_section].Range.Paragraphs[1].Range;
            cur_Range.Select();

             str = wordContent.Text;
            oWord.Options.Overtype = false;
            MsWord.Selection cur_Selection = oWord.Selection;
            float leftPosition = (float)oWord.Selection.Information[MsWord.WdInformation.wdHorizontalPositionRelativeToPage];
            float toptPosition = (float)oWord.Selection.Information[MsWord.WdInformation.wdVerticalPositionRelativeToPage];

            oDoc.Shapes.AddTextEffect(Microsoft.Office.Core.MsoPresetTextEffect.msoTextEffect29, str,
    "微软雅黑", 24, Microsoft.Office.Core.MsoTriState.msoFalse, Microsoft.Office.Core.MsoTriState.msoFalse,
    leftPosition, toptPosition);
          
            //关闭并保存文件
            object fileName = docFileName;
            oDoc.SaveAs2(ref fileName);
            oDoc.Close();
        }

二、操作excel

相对于操作word,操作excel就简单多了,for循环基本可以实现大部分操作。

首先演示一下如何获取单元格中的信息,为了方便这里只是简单是获取一个个单元格中的数据,加入到一个字符串中(excelContent.Text):

 //显示表格信息到窗体页面
        public void showCells(object sender, RoutedEventArgs e)
        {
            //文件名
            string dest_file_name = Directory.GetCurrentDirectory() + @"\abc.xlsx";
            MsExcel.Application oExcApp;//Excel Application;
            MsExcel.Workbook oExcBook;//Excel Book

            object isread = false;
            object isvisible = true;
            object filename = dest_file_name;

            oExcApp = new MsExcel.Application();
            object miss = System.Reflection.Missing.Value;
            oExcBook = oExcApp.Workbooks.Open(dest_file_name);

            MsExcel.Worksheet worksheet1 = (MsExcel.Worksheet)oExcBook.Worksheets["sheet1"];	//注意这里选择的是sheet1
            worksheet1.Activate();
            //至此,基本就打开完成了
            oExcApp.Visible = false;
            oExcApp.DisplayAlerts = false;
            MsExcel.Range range1 = worksheet1.get_Range("A1", "G1");
            range1.Columns.ColumnWidth = 8;
            range1.Columns.RowHeight = 20;
            range1.Merge(false);
            range1.Font.Size = 20;
            range1.Font.Bold = true;
            range1.Columns.ColumnWidth = 7;
            range1.Columns.RowHeight = 10;
            String str = "";
            for(int j = 1; j <= 9; j++)
            {
                for (char i = 'A'; i <= 'G'; i++)
                    
                {
                    str = "";
                    str += i;
                    str += j;
                    excelContent.Text += worksheet1.Range[str].Value2;
                    excelContent.Text +="\t";
                }
                excelContent.Text += "\n\r";
                
            }

        }

1.添加图表

添加图表的过程比较麻烦,大概如下:

  1. 打开excel,同之前一样,声明变量
  2. 选中单元格范围用于制作表格
  3. 设置图表样式
  4. 设置图表属性
  5. 刷新,关闭,释放

参考代码:

        //向Excel中添加图表
        public void addChart(object sender, RoutedEventArgs e)
        {
            /*
            	打开excel的操作,和上面完全一致,这里省略
            */

            MsExcel.Worksheet worksheet1 = (MsExcel.Worksheet)oExcBook.Worksheets["sheet1"];
            worksheet1.Activate();
            oExcApp.Visible = false;
            oExcApp.DisplayAlerts = false;
            MsExcel.Range range1 = worksheet1.get_Range("A1", "G10");
            range1.Borders.LineStyle = MsExcel.XlLineStyle.xlLineStyleNone;
            range1.Borders.Color = MsExcel.XlRgbColor.rgbBlack;

            MsExcel.Shape theShape = worksheet1.Shapes.AddChart(MsExcel.XlChartType.xl3DColumn, 120, 130, 380, 250);
            MsExcel.Range range = worksheet1.get_Range("A1:G10");
            theShape.Chart.SetSourceData(range, Type.Missing);

            theShape.Chart.HasTitle = true;
            theShape.Chart.ChartTitle.Text = "一些数据";
            theShape.Chart.ChartTitle.Caption = "一些数据";

        }

其实对于个人来说用com组件操作office又麻烦又折磨,还是用软件操作比较好。当然想批量操作的话可以参考上面的方法做一种批量操作的小软件,占用的内存还小。

posted @ 2021-12-31 23:36  CinqueOrigin  阅读(1175)  评论(0)    收藏  举报