使⽤com组件操作word和excel
com组件对于我来说⼀直很谜,尤其是操作word和excel部分,今天在这好好整理⼀下⽤到的知识。
本次使⽤的语⾔是c#,代码仅供参考。
⼀、操作
⾸先添加对这个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._Item(ref wd_FontSize_Index).ParagraphFormat.Alignment = MsWord.WdParagraphAlignment.wdAlignParagraphCenter; oWord._Item(ref wd_FontSize_Index).Font.Name = "微软雅⿊";
oWord._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();
}
⼆、操作
相对于操作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 = _Range("A1", "G1");
range1.Columns.ColumnWidth = 8;
range1.Columns.RowHeight = 20;
range1.Merge(false);
range1.Font.Size = 20;
range1.Font.Bold = true;
positionrelative啥意思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 = _Range("A1", "G10");
range1.Borders.LineStyle = MsExcel.XlLineStyle.xlLineStyleNone;
range1.Borders.Color = bBlack;
MsExcel.Shape theShape = worksheet1.Shapes.AddChart(MsExcel.XlChartType.xl3DColumn, 120, 130, 380, 250);
MsExcel.Range range = _Range("A1:G10");
theShape.Chart.SetSourceData(range, Type.Missing);
theShape.Chart.HasTitle = true;
theShape.Chart.ChartTitle.Text = "⼀些数据";
theShape.Chart.ChartTitle.Caption = "⼀些数据";
}
其实对于个⼈来说⽤com组件操作office⼜⿇烦⼜折磨,还是⽤软件操作⽐较好。当然想批量操作的话可以参考上⾯的⽅法做⼀种批量操作的⼩软件,占⽤的内存还⼩。
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论