目前我正在开发一个Windows窗体应用程序。首先,我使用for循环,它工作得很好,但数据变得更大,并开始生成文件非常慢。我切换到并行循环,它在“document.Save(fileName +”。pdf“)上抛出并且异常”参数无效“;”
以下是我的代码片段
private void btnGenerateFiles_Click(object sender, EventArgs e)
{
if (labelDataSrc.Text == string.Empty || labelTemplateSrcBG.Text == string.Empty)
{
MessageBox.Show("Template or Data files are not set");
return;
}
ComponentInfo.SetLicense("FREE-LIMITED-KEY");
DocumentModel document = DocumentModel.Load(Globals.pathTemplateSrcBG); ;
Excel.Application objExcel = new Excel.Application();
objExcel.Visible = true;
Excel.Workbook objBook = objExcel.Workbooks.Open(Globals.pathDataSrc);
Excel.Worksheet objsheet = objBook.Worksheets["Sheet2"];
var range = objsheet.UsedRange;
var rCnt = range.Rows.Count;
Parallel.For(2, rCnt, i =>
{
if (objsheet.Cells.get_Item(i, "D").Value == "BG")
{
document = DocumentModel.Load(Globals.pathTemplateSrcBG);
}
else if (objsheet.Cells.get_Item(i, "D").Value == "ENG")
{
document = DocumentModel.Load(Globals.pathTemplateSrcENG);
}
else if (objsheet.Cells.get_Item(i, "D").Value == "RO")
{
document = DocumentModel.Load(Globals.pathTemplateSrcRO);
}
else
{
MessageBox.Show("No language of communication on line " + i);
}
// Find and replace text.
document.Content.Replace("*ClnName*", Convert.ToString(objsheet.Cells.get_Item(i, "A").Value) + " " + Convert.ToString(objsheet.Cells.get_Item(i, "B").Value));
document.Content.Replace("*clnContractNum*", Convert.ToString(objsheet.Cells.get_Item(i, "F").Value));
document.Content.Replace("*DateSigned*", DateTime.Now.ToString("dd.MM.yyyy"));
string fileName = Convert.ToString(objsheet.Cells.get_Item(i, "F").Value).Replace(@"/", @"-");
document.Save(fileName + ".pdf");
labelProgress.Text = i + "/" + rCnt;
Application.DoEvents();
});
}
很抱歉,如果我的问题很愚蠢,但是我正在敲打那个问题并在几小时内寻找解决方案。
提前致谢!