我正在编写一个程序来用数据填充 Excel 工作簿,但目前我只能访问第一张工作表。
通过这个测试,我无法让 sheet2 和 Sheet3 接收任何数据?
请有人指出我错过了什么?
Excel.Application xlApp;
Excel.Workbook xlWorkBook;
Excel.Worksheet[] xlWorkSheet = new Excel.Worksheet[3];
object misValue = System.Reflection.Missing.Value;
private void Form1_Load(object sender, EventArgs e)
{
if (File.Exists("C:/Users/Shaun/Documents/Template.xls"))
{
//Load Templete SpreadSheet
xlApp = new Excel.ApplicationClass();
xlWorkBook = xlApp.Workbooks.Open("Template.xls", 0, true, 5, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
xlWorkSheet[0] = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
xlWorkSheet[1] = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
xlWorkSheet[2] = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
}
else
{
MessageBox.Show("Could not find file Template.xls");
}
}
private void button1_Click(object sender, EventArgs e)
{
xlWorkSheet[0].Cells[1, 1] = "Sheet1";
xlWorkSheet[1].Cells[1, 1] = "Sheet2";
xlWorkSheet[2].Cells[1, 1] = "Sheet3";
String Saveas;
Saveas = Microsoft.VisualBasic.Interaction.InputBox("Save As", "Save As", "");
xlWorkBook.SaveAs(Saveas + ".xls", Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
xlWorkBook.Close(true, misValue, misValue);
xlApp.Quit();
for (int p = 0; p < 3; p++)
{
releaseObject(xlWorkSheet[p]);
}
releaseObject(xlWorkBook);
releaseObject(xlApp);
MessageBox.Show("File Saved!");
}
private void releaseObject(object obj)
{
try
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
obj = null;
}
catch (Exception ex)
{
obj = null;
MessageBox.Show("Unable to release the Object " + ex.ToString());
}
finally
{
GC.Collect();
}
}
编辑
即使有了这个改变,仍然没有任何事情发生,除了第一张,我不能拿起任何床单。
xlWorkSheet[0] = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
xlWorkSheet[1] = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(2);
xlWorkSheet[2] = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(3);