我從這裏得到了一些代碼:http://forum.codecall.net/topic/71788-reading-excel-files-in-c/,它工作正常,對我來說很容易理解。它只能讀取excel單元格,我也想寫一些。 所以我想在我的主要做到這一點:excel_setValue(「C10」,「520」);在excel中寫入單元格的函數
這是我試過的功能:
private static Microsoft.Office.Interop.Excel.ApplicationClass appExcel;
private static Workbook newWorkbook = null;
private static _Worksheet objsheet = null;
static string excel_setValue(string cellname, string value)
{
if (objsheet.get_Range(cellname).get_Value().ToString() == string.Empty) // Here is error
{
Console.WriteLine("watch out u trying to overwrite files");
}
else
{
objsheet.get_Range(cellname).set_Value(value);
}
}
它告訴我:NullReferenceExpection是未處理的 - 不設置到對象的實例對象引用。
另一個錯誤我的時候,我只把這個:
static void excel_setValue(string cellname, string value)
{
//if (objsheet.get_Range(cellname).get_Value().ToString() == string.Empty)
//{
// Console.WriteLine("kijk uit je probeerd cellen te overschrijven");
//}
//else
//{
objsheet.get_Range(cellname).set_Value(value);
//}
}
錯誤:收到COMException是未處理的:從HRESULT異常:0x800A03EC
我如何打電話給我excel_setValue:
excel_init("C:\\");
excel_setValue("B10","520");
excel_init :
static void excel_init(String path)
{
appExcel = new Microsoft.Office.Interop.Excel.ApplicationClass();
if (System.IO.File.Exists(path))
{
// then go and load this into excel
newWorkbook = appExcel.Workbooks.Open(path, true, true);
objsheet = (_Worksheet)appExcel.ActiveWorkbook.ActiveSheet;
}
else
{
Console.WriteLine("Unable to open file!");
System.Runtime.InteropServices.Marshal.ReleaseComObject(appExcel);
appExcel = null;
}
}
如果get_Range返回null,你會得到錯誤的get_value()。請顯示你如何調用excel_setValue方法。 – JWiley
在這個方法中(這個範圍),'objsheet'不存在。還是在封裝類中定義? – Melvin
在我的主要問題中編輯了這2個問題 – wouter