我正在尝试在服务器上创建并保存一个 excel 文件,然后将其作为文档发送。在添加附件时,我遇到了错误。任何人都有任何想法,我该如何解决?
The process cannot access the file because it is being used by another process
请找到我用来创建 excel 文件和返回路径的代码,稍后将其添加为文档:
Microsoft.Office.Interop.Excel.ApplicationClass excel = new Microsoft.Office.Interop.Excel.ApplicationClass();
string attachmentPath = Convert.ToString(ConfigurationManager.AppSettings["AttachmentPath"] as object);
string path = attachmentPath + FileName;
excel.Application.Workbooks.Add(true);
int ColumnIndex = 0;
foreach (DataColumn col in table.Columns)
{
ColumnIndex++;
excel.Cells[1, ColumnIndex] = col.ColumnName;
}
int rowIndex = 0;
foreach (DataRow row in table.Rows)
{
rowIndex++;
ColumnIndex = 0;
foreach (DataColumn col in table.Columns)
{
ColumnIndex++;
excel.Cells[rowIndex + 1, ColumnIndex] = row[col.ColumnName].ToString();
}
}
excel.DisplayAlerts = false;
excel.ActiveWorkbook.SaveAs(path, Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookNormal, Type.Missing, Type.Missing,
false, false, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange,
Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
excel.Quit();
return path + ".xls";
下面是我使用上述路径添加为电子邮件附件的代码:
if (attachmentPaths != null && attachmentPaths.Length > 0)
{
foreach (string path in attachmentPaths)
{
if (!string.IsNullOrEmpty(path))
message.Attachments.Add(new System.Net.Mail.Attachment(path));
}
}
SmtpClient smtp = new SmtpClient(objBO.SmtpDomain);
smtp.Send(message);
请提供建议。提前致谢。