【发布时间】:2015-05-04 16:14:27
【问题描述】:
我正在使用SpreadsheetLight 从 WinForms 项目中写入日志文件。我的意图是将日志条目写入同一个文件中的三个工作表,如果可以避免,我真的想避免使用Interop。
我从一个用 Excel 制作的模板文件开始,其中预先填充了三个工作表的行标题,并且由于每个工作表具有相同的基本属性(可以独立变化),我将每个工作表封装在一个类中,基础其中看起来像这样:
/// <summary>
/// Encapsulate the info we need to know about each worksheet in order to populate properly
/// </summary>
public class LogSheet
{
public SLDocument data;
public SLWorksheetStatistics stats;
public int RowCount;
public int ColumnCount;
public int currentColumn; //indicates what column you want to be writing to
public List<string> rowNames = new List<string>(); //used to make sure you're writing new data to the right row
public List<string> columnNames = new List<string>(); //used by GetLatestRun() to check if data already exists for a given serial number
public LogSheet(string sheet)
{
this.data = new SLDocument(_path, sheet);
this.stats = this.data.GetWorksheetStatistics();
this.RowCount = this.stats.EndRowIndex;
this.ColumnCount = this.stats.EndColumnIndex;
currentColumn = GetLatestRun();
for (int i = 1; i < RowCount + 1; i++)
{
this.rowNames.Add(this.data.GetCellValueAsString(i, 1));
}
for (int i = 1; i < ColumnCount + 1; i++)
{
this.columnNames.Add(this.data.GetCellValueAsString(1, i));
}
}
}
还有一些在LogSheet 类中未显示的方法来处理将数据写入正确的位置。
这一切似乎工作正常,在调试时,我可以看到用new LogSheet(<sheetName>) 实例化的三个工作表中的每一个都包含我写东西后它们应该包含的数据。
问题是当我想保存数据时,我可以使用this.data.Save(),但它只保存一个工作表,而另外两个现在处于不确定状态,因为Save() 方法是终端并关闭Excel 文件。在其他任何一张纸上尝试Save() 方法,最终都会出现异常"Object reference not set to an object",因为Save() 杀死了我的电子表格,并且这些纸不再有任何可参考的内容。结果文件只有我第一次保存时的数据。
对于如何解决这个问题,我最好的猜测是不要为每张工作表实例化一个新的SLDocument,而是在每次我想写到一个特定的工作表时使用SLDocument.SelectWorksheet(),但我仍然想把东西封装在LogSheet 类,因为其中的所有其他内容仍然相关。
还有其他建议吗?
【问题讨论】:
标签: c# worksheet spreadsheetlight