我对 C# word 文档有一点问题。我使用 Word.Interop 库来创建一个 .doc 文档。我在这个文档中放入了一个动态表,在最后一列中有一些文本和图片我的问题是保存/生成文档真的很慢(表中只有 30 行需要 4 秒,54 行需要 7 秒)。对我来说时间太多了。我需要在大约 1 秒或更短的时间内创建和保存文档。
有什么方法可以比 Word.Interop 更快地创建文档?也许模板文件?但是如何从模板文档中填充动态大小的表格呢?
Microsoft.Office.Interop.Word.Application WordApp = new Microsoft.Office.Interop.Word.Application();
Word.Document adoc;
Word.Range rng;
adoc = WordApp.Documents.Add(ref missing, ref missing, ref missing, ref missing);
rng = adoc.Range(ref start1, ref missing);
adoc.Tables.Add(rng, list.Count + 2, 4);
adoc.PageSetup.LeftMargin = 20.0f;
adoc.PageSetup.RightMargin = 20.0f;
adoc.Tables[1].Columns[2].Cells.PreferredWidth = 60;
adoc.Tables[1].Columns[1].Cells.PreferredWidth = 200;
adoc.Tables[1].Cell(1, 1).Range.Text = "Symbol";
adoc.Tables[1].Cell(1, 2).Range.Text = "Qnt";
adoc.Tables[1].Cell(1, 3).Range.Text = "Barcode";
adoc.Tables[1].Cell(1, 4).Range.Text = "Barcode Image";
adoc.Tables[1].Cell(1, 1).Range.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphLeft;
adoc.Tables[1].Cell(1, 1).Range.Font.Bold = 1;
adoc.Tables[1].Cell(1, 2).Range.Font.Bold = 1;
adoc.Tables[1].Cell(1, 3).Range.Font.Bold = 1;
adoc.Tables[1].Cell(1, 4).Range.Font.Bold = 1;
for (int i = 0; i < list.Count; i++)
{
adoc.Tables[1].Cell(i + 2, 1).Range.Text = list[i].symbol;
adoc.Tables[1].Cell(i + 2, 2).Range.Text = list[i].qnt;
adoc.Tables[1].Cell(i + 2, 3).Range.Text = list[i].code;
adoc.Tables[1].Cell(i + 2, 4).Range.InlineShapes.AddPicture(list[i].code_picture, ref missing, ref missing, ref missing);
}
adoc.Tables[1].Range.Font.Size = 10;
adoc.Tables[1].Rows.Height = 2.0f;
#region Border
adoc.Tables[1].Borders[Word.WdBorderType.wdBorderLeft].LineStyle = Word.WdLineStyle.wdLineStyleSingle;
adoc.Tables[1].Borders[Word.WdBorderType.wdBorderTop].LineStyle = Word.WdLineStyle.wdLineStyleSingle;
adoc.Tables[1].Borders[Word.WdBorderType.wdBorderRight].LineStyle = Word.WdLineStyle.wdLineStyleSingle;
adoc.Tables[1].Borders[Word.WdBorderType.wdBorderBottom].LineStyle = Word.WdLineStyle.wdLineStyleSingle;
adoc.Tables[1].Borders[Word.WdBorderType.wdBorderHorizontal].LineStyle = Word.WdLineStyle.wdLineStyleSingle;
adoc.Tables[1].Borders[Word.WdBorderType.wdBorderVertical].LineStyle = Word.WdLineStyle.wdLineStyleSingle;
#endregion
try
{
object filename = @"E:\Test.doc";
adoc.SaveAs(ref filename, ref missing, ref missing, ref missing, ref missing, ref missing,
ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing);
// Word.Table wt1 = WordApp.Selection.Tables.Add(WordApp.Selection.Range, 5, 2, ref missing, ref missing);
//adoc.Tables[1].Rows.Add(adoc.Tables[1].Rows[1]);
//WordApp.Visible = true;
//adoc.Close();
WordApp.Quit(ref missing, ref missing, ref missing);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}