目前,我有一些代码能够创建文件,创建新工作表,更改活动工作表,但它不会写入单元格。以下是我的代码:
var excelApp = new Excel.Application
{
Visible = false,
ScreenUpdating = false
};
object misValue = System.Reflection.Missing.Value;
var workbook = excelApp.Workbooks.Add(misValue);
var worksheets = workbook.Worksheets;
var worksheet = (Excel.Worksheet)workbook.ActiveSheet;
worksheet.Cells[3, 3].Value2 = "123"; //This is the part where I'm struggling
workbook.SaveAs(completePathToFile, Excel.XlFileFormat.xlWorkbookNormal);
workbook.Close();
目前情况如何,它抛出:
Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: 'Cannot perform runtime binding on a null reference'
当我试图将其值设置为非null时,为什么它会抛出这一点毫无意义。我也尝试删除Value2并直接设置单元格。错误消失了,但它仍然没有写入.xls文件。
答案 0 :(得分:0)
尝试
m_objBook = (Excel._Workbook)(m_objBooks.Add(m_objOpt));
(Excel.Workbooks)m_objExcel.Workbooks;
//Start a new workbook in Excel.
m_objExcel = new Excel.Application();
//Add data to cells in the first worksheet in the new workbook.
m_objSheets = (Excel.Sheets)m_objBook.Worksheets;
m_objSheet = (Excel._Worksheet)(m_objSheets.get_Item(1));
m_objRange = m_objSheet.Range["A1", m_objOpt);
m_objRange.Value = "Last Name";
m_objRange = m_objSheet.Range["B1", m_objOpt);
m_objRange.Value = "First Name";
m_objRange = m_objSheet.Range["A2", m_objOpt);
m_objRange.Value = "Doe";
m_objRange = m_objSheet.Range["B2", m_objOpt);
m_objRange.Value = "John";
//Apply bold to cells A1:B1.
m_objRange = m_objSheet.Range["A1", "B1");
m_objFont = m_objRange.Font;
m_objFont.Bold = true;
//Save the Workbook and quit Excel.
m_objBook.SaveAs(m_strSampleFolder + "Book1.xls", m_objOpt, m_objOpt,
m_objOpt, m_objOpt, m_objOpt, Excel.XlSaveAsAccessMode.xlNoChange,
m_objOpt, m_objOpt, m_objOpt, m_objOpt);
m_objBook.Close(false, m_objOpt, m_objOpt);
m_objExcel.Quit();