我在Windows窗体应用程序中创建了一个实用程序,它读取文本文件并执行一些业务逻辑,然后将该数据导出到excel,对于excel处理,我使用了Microsoft Excel XX.X对象库。我添加了以下方法,用于初始化Excel库对象,然后向其中添加数据。
用于创建Excel文档:
public void createDoc()
{
try
{
app = new Excel.Application();
//app.Visible = true;
workbook = app.Workbooks.Add(1);
worksheet = (Excel.Worksheet)workbook.Sheets[1];
}
catch (Exception e)
{
MessageBox.Show(e.Message);
}
finally
{
}
}
用于向excel添加数据:
public void addData(int row, int col, string data)
{
try
{
worksheet.Cells[row, col] = data;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
然后我添加了以下代码以在后台运行:
void backgroundProcess(object sender, DoWorkEventArgs e)
{
SpecialCharacter specialCharObj = new SpecialCharacter();
//creating excel Doc
CreateExcelDoc excell_app = new CreateExcelDoc();
//creates the main header
excell_app.createHeaders();
string[] readText = File.ReadAllLines(txtAddFile.Text);
//MsgLabel.Text = "Exporting to excel......";
foreach (string s in readText)
{
specialCharObj.setAllFields(s);
excell_app.addDataToExcel(specialCharObj,count);
count++;
bgw.ReportProgress(count-2);
}
excell_app.writeDoc(txtAddFile.Text.ToString()+"_Output.xlsx");
}
addDataToExcel调用excel类的addData方法,该方法在Excel工作表中添加多个字段,如下所示:
public void addDataToExcel(SpecialCharacter obj,int count)
{
this.addData(count, 1, "Debenhams");
this.addData(count, 2, obj.identifier);
this.addData(count, 3, obj.date);
this.addData(count, 4, obj.referenceNo);
this.addData(count, 5, obj.IdentificationCode);
this.addData(count, 6, obj.franchiseName);
this.addData(count, 7, obj.storeNum);
this.addData(count, 8, obj.InvoiceNum);
this.addData(count, 9, obj.divisionNum);
}
现在我面临的真正问题是我有一个表单关闭方法,在处理之间处理关闭表单的工作,方法编写如下:
private void DebenhamsSpecialCharUtility_FormClosing(object sender, FormClosingEventArgs e)
{
if (MsgLabel.Text == "Exported")
{
Application.Exit();
}
else
{
if (e.CloseReason == CloseReason.UserClosing)
{
DialogResult result = MessageBox.Show("Do you really want to exit?", "Dialog Title", MessageBoxButtons.YesNo);
if (result == DialogResult.Yes)
{
//excell_app.excelAppClose();
Application.Exit();
}
else
{
e.Cancel = true;
}
}
else
{
e.Cancel = true;
}
}
现在我需要做的是结束我在后台运行的excel处理,如果用户在处理期间关闭表单,但是如果我这样做会引发异常,因为它循环遍历文件并添加数据到excel,因此无法释放Excel对象。我使用以下代码来释放excel对象:
workbook.Close(true, misValue, misValue);
app.Quit();
System.Runtime.InteropServices.Marshal.ReleaseComObject(app);
所以我需要有人为我提供结束流程的解决方案,而不会引发任何异常,因为它循环遍历数据并将数据添加到Excel中。