我有一個Windows應用程序,提交後創建一個Excel文件(如果尚未創建)或附加到Excel文件。該文件每次都在創建,但我也收到一條消息,詢問是否要複製該文件。我想附加到該文件不重寫該文件。有人能告訴我我做錯了什麼嗎?保存數據到Excel
下面是我的提交功能,我的代碼:
string filePath = "C:\\Temp\\test.xlsx";
Excel.Application oApp;
Excel.Worksheet oSheet;
Excel.Workbook oBook;
oApp = new Excel.Application();
oBook = oApp.Workbooks.Add();
oSheet = (Excel.Worksheet)oBook.Worksheets.get_Item(1);
if (!File.Exists(filePath))
{
using (File.CreateText(filePath))
{
oSheet.Cells[1, 2] = "First Name"; oSheet.Cells[1, 3] = "Last Name"; oSheet.Cells[1, 4] = "Street Address"; oSheet.Cells[1, 5] = "City"; oSheet.Cells[1, 6] = "State";
oSheet.Cells[1, 7] = "Zip Code"; oSheet.Cells[1, 8] = "Phone"; oSheet.Cells[1, 9] = "Email"; oSheet.Cells[1, 10] = "DOB"; oSheet.Cells[1, 11] = "Gender"; oSheet.Cells[1, 12] = "High School";
oSheet.Cells[1, 13] = "Graduation Year"; oSheet.Cells[1, 14] = "Planned Term"; oSheet.Cells[1, 15] = "Intended Major";
oSheet.Cells[2, 2] = txtFirstName.Text; oSheet.Cells[2, 3] = txtLastName.Text; oSheet.Cells[2, 4] = txtAddress.Text; oSheet.Cells[2, 5] = txtCity.Text; oSheet.Cells[2, 6] = txtState.Text;
oSheet.Cells[2, 7] = txtZipCode.Text; oSheet.Cells[2, 8] = txtPhone.Text; oSheet.Cells[2, 9] = txtEmail.Text; oSheet.Cells[2, 10] = dtpDOB.Value; oSheet.Cells[2, 11] = genderSet.ToString();
oSheet.Cells[2, 12] = txtHighSchool.Text; oSheet.Cells[2, 13] = txtGraduationYear.Text; oSheet.Cells[2, 14] = txtTermofEnrollment.Text; oSheet.Cells[2, 15] = outText.ToString();
}
}
else
{
using (File.AppendText(filePath))
{
oSheet.Cells[2, 2] = txtFirstName.Text; oSheet.Cells[2, 3] = txtLastName.Text; oSheet.Cells[2, 4] = txtAddress.Text; oSheet.Cells[2, 5] = txtCity.Text; oSheet.Cells[2, 6] = txtState.Text;
oSheet.Cells[2, 7] = txtZipCode.Text; oSheet.Cells[2, 8] = txtPhone.Text; oSheet.Cells[2, 9] = txtEmail.Text; oSheet.Cells[2, 10] = dtpDOB.Value; oSheet.Cells[2, 11] = genderSet.ToString();
oSheet.Cells[2, 12] = txtHighSchool.Text; oSheet.Cells[2, 13] = txtGraduationYear.Text; oSheet.Cells[2, 14] = txtTermofEnrollment.Text; oSheet.Cells[2, 15] = outText.ToString();
}
}
'SaveAs'方法將保存對工作簿的更改在一個**不同的文件**。 – luke2012