下面的这个方法因为dataset里的数据有1900多行,导致整个word生成失败, 这个方法的主要功能是,添加行数据到表格,并将数据复制到head.doc模板,在另存为一个新的word文件。红色部分是调试的时候,一直没有执行完的地方。(实际上数据是生成完了的,但都是在临时文件里。。。具体可能要清楚的朋友的才能明白),请大家提点建议,谢谢!
private bool AddTableRow(string fileName, int addRowCount,DataSet ds )
{
Word.ApplicationClass cls = null;
Word.Document doc = null;
Word.Table table = null;
object missing = System.Reflection.Missing.Value;
object path = fileName;
cls = new Word.ApplicationClass();
try
{
doc = cls.Documents.Open
(ref path, 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);
table = doc.Tables[1];
//object newRow = table.Rows[1];
for (int i = 0; i < addRowCount; i++)
{
Word.Row row = table.Rows[1];
DataRow dr = ds.Tables[0].Rows[i];
row.Cells[1].Range.Text = dr[0].ToString();
row.Cells[2].Range.Text = dr[1].ToString();
row.Cells[3].Range.Text = dr[2].ToString();
row.Cells[4].Range.Text = dr[3].ToString();
row.Cells[5].Range.Text = dr[4].ToString();
row.Cells[6].Range.Text = dr[5].ToString();
object newRow = row;
table.Rows.Add(ref newRow);
}
doc.Content.Copy();
#region //删除生成的表格,并保存,因为操作插入行后就已经修改了该模板,所以撤销显然麻烦些,干脆删除生成的行,然后在保存这样模板就等于是还原了
//while (doc.Tables[1].Rows.Count > 1)
//{
// doc.Tables[1].Rows[1].Delete();
//}
object savechange = Word.WdSaveOptions.wdDoNotSaveChanges;
doc.Close(ref savechange, ref missing, ref missing);
#endregion
path = dirRootPath + tempDirName + "\\head.doc";
doc = cls.Documents.Open
(ref path, 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);
doc.Content.Paragraphs.Last.Range.Paste();
string bluidPsReportPath = FindOrCreateDir(dirRootPath, "4", this.labID);
object newpath = bluidPsReportPath + "\\" + DateTime.Now.ToString("yyyy-MM-dd") + this.bulidReportName + ".doc";
doc.SaveAs(ref newpath, 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);
return true;
}
catch (Exception ex)
{
return false;
}
finally
{
if (doc != null)
{
doc.Close(ref missing, ref missing, ref missing);
cls.Quit(ref missing, ref missing, ref missing);
}
}
return true;
}
1把这个方法放在backgroundwork执行下看看是不是效果会好点
2Word.Row row = table.Rows[1]; 是1还是i 如果是1的话能否放在循环外面
3object newRow = row;能否把定义newrow放在循环外面,循环内只赋值
4如果把行数减小能否执行成功