所以我有一個窗口下面的代碼:ExcelWorksheet尺寸的NullReferenceException
public partial class List : Window
{
DataTable table = null;
ExcelWorksheet ws = null;
string user = System.Environment.UserName;
public void Initialize()
{
string path = "Log.xlsx";
FileInfo file = new FileInfo(path);
try
{
if (File.Exists(path))
{
using (ExcelPackage pack = new ExcelPackage(file))
{
bool sheetfound = false;
//runs through each sheet to find a specific one
foreach (ExcelWorksheet sheet in pack.Workbook.Worksheets)
{
if (sheet.Name.Equals(user))
{
sheetfound = true;
ws = pack.Workbook.Worksheets[user];
break;
}
}
//Creates new sheet if it hasn't found the specific one
if (!(sheetfound))
{
ws = MainWindow.Create_Worksheet(pack);
pack.Save();
}
}
}
else
{
using (ExcelPackage pack = new ExcelPackage(file))
{
ExcelWorksheet ws = MainWindow.Create_Worksheet(pack);
pack.Save();
}
}
}
catch (Exception ex)
{
MessageBox.Show("Exception caught:\n\n" + ex as string, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
}
fUpdate(new Object, new RoutedEventArgs);
}
public void fUpdate(object sender, RoutedEventArgs e)
{
table.Rows.Clear();
MessageBox.Show(ws.Dimension.End.Row.ToString());
}
}
而這一次從主窗口:
public partial class MainWindow : Window
{
public static ExcelWorksheet Create_Worksheet(ExcelPackage pack)
{
ExcelWorksheet ws = pack.Workbook.Worksheets.Add(System.Environment.UserName);
ws.Cells[1, 1].Value = "Date";
ws.Cells[1, 2].Value = "Time";
ws.View.FreezePanes(2, 1);
return ws;
}
}
什麼,這是應該做的,現在,第二時窗口啓動後,它會設置Excel文件和工作表。我使用了Quickwatch來查看它是否正常工作,並且它確實起作用,ws被設置爲我想要的特定工作表,並且ws.Dimension.End.Row
返回1.但是,在它離開try-catch部分(一旦達到fUpdate)之後,ws.Dimension.End.Row
突然拋出一個NullReferenceException。我查了一下,ws仍然是ExcelWorksheet對象,它沒有經過任何(我知道的)會改變它的值。什麼導致這個錯誤?謝謝!
(ws
返回ExcelWorksheet對象,但ws.Dimensions
返回除外)
可能重複[什麼是NullReferenceException,以及如何解決它?](https://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-doi-i-fix -it) –