我有2个工作表的Excel文件,当我尝试成功地从文本框中输入数据到工作表1时,但是当我尝试在工作表2中输入数据时,第一个工作表命名为“ PM”,第二个工作表命名为“ km”。工作表1返回到其原始状态(空)。 我检查了我在两个工作表的第一个工作表“ xlsht”上创建的代码,但未在两个工作表上更新数据,然后我用两个工作表进行了2个功能,但问题是相同的,知道为什么吗?
我的代码:
protected void PM_Sheet1()
{
try
{
Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();
Worksheet xlsht = new Worksheet();
string path = @"D:\test.xlsx";
xlsht = xlApp.Application.Workbooks.Open(path).Worksheets["PM"];
xlsht.Cells[11, 2] = UserNameTxt.Text + "@rasatop.com";
xlsht.Cells[11, 4] = UserNameTxt.Text;
xlsht.Cells[14, 2] = SerialTxt.Text;
xlsht.Cells[16, 2] = WLANMacTxt.Text;
xlsht.Cells[16, 3] = LANMacTxt.Text;
xlsht.Cells[16, 4] = IPTxt.Text;
xlsht.Cells[14, 5] = ComputerTxt.Text;
xlsht.Cells[16, 5] = BarcodeTxt.Text;
xlsht.Cells[18, 5] = CPUTxt.Text.Substring(0, 26);
xlsht.Cells[18, 4] = VGATxt.Text;
xlsht.Cells[18, 3] = RAMTxt.Text;
xlsht.Cells[27, 4] = OSTxt.Text;
xlsht.Cells[5, 4] = System.DateTime.Today;
xlsht.Cells[26, 4] = System.DateTime.Today;
xlsht.Cells[9, 5] = System.DirectoryServices.AccountManagement.UserPrincipal.Current.DisplayName;
xlsht.SaveAs(@"D:\test1.xlsx");
}
catch (Exception)
{
MessageBox.Show(@"Make Sure test.xlsx file in D:\ Drive");
}
}
protected void PM_Sheet2()
{
try
{
Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();
Worksheet xlsht = new Worksheet();
string path = @"D:\test1.xlsx";
xlsht = xlApp.Application.Workbooks.Open(path).Worksheets["km"];
xlsht.Cells[4, 2] = System.DateTime.Today;
xlsht.Cells[6, 2] = UserNameTxt.Text;
xlsht.Cells[6, 4] = ComputerTxt.Text;
xlsht.Cells[6, 5] = BarcodeTxt.Text;
xlsht.SaveAs(@"D:\" + ComputerTxt.Text + ".xlsx");
xlApp.Visible = true;
}
catch (Exception)
{
MessageBox.Show("Error Occured Cannot Save Sheet 2");
}
}
答案 0 :(得分:0)
尽管documentation,Worksheet.SaveAs()
会导致错误,所以您必须使用Workbook.SaveAs()
您还将打开两个不同的Excel实例,其中只需要一个实例,并且显然使它们都在运行!
最后,最好打开所有操作的Excel实例,并因此在Form
类级别(声明),button1_Click()
级别(Excel
和{{1} }初始化),辅助方法(Workbook
初始化)
如下:
Worksheet