我正在关注this posts建议并尝试释放所有COM对象,包括将字符串元组列表写入Excel电子表格(使用他的ComObjectManager类)时的所有范围。
我在下面的解决方案有效,但看起来并没有堆叠
引入的Range COM对象cells[j, column] = strings[i].Item1;
(等)在ComObjectManager对象中,因此不释放它们。我有一个注释掉的解决方案,可以释放对象,但我不能正确理解设置单元格的语法,因为它不会编译。我也尝试过使用
var roomNameCell = com.Get<object>(() => cells[j, column]);
对于roomNameCell和areaCell,但这导致没有任何内容被写入单元格。
我已经研究过MSDN指南,但无法弄清楚如何做到这一点,请帮助。
internal void InsertStrings(List<Tuple<string, string>> strings, Excel.Range selection, ComObjectManager com)
{
const int singleRowCell = 1;
const int columnsToArea = 2;
int firstRow = selection.Row;
int column = selection.Column;
for (int i = 0, j = firstRow; i < strings.Count; )
{
selection = com.Get<Excel.Range>(() => app.Cells[j, column]);
var mergeArea = com.Get<Excel.Range>(() => selection.MergeArea);
var mergeAreaRows = com.Get<Excel.Range>(() => mergeArea.Rows);
var cells = com.Get<Excel.Range>(() => app.Cells);
if (selection.MergeCells && mergeAreaRows.Count > singleRowCell)
{
//var roomNameCell = com.Get<Excel.Range>(() => cells[j, column]);
//var areaCell = com.Get<Excel.Range>(() => cells[j, column + columnsToArea]);
//doesn't compile - cannont explicity convert from string to Range
//roomNameCell = strings[i].Item1;
//areaCell = strings[i].Item2;
//works but the Range COM objects aren't being disposed?
cells[j, column] = strings[i].Item1;
cells[j, column + columnsToArea] = strings[i].Item2;
++i;
}
j += mergeAreaRows.Count;
}
}
答案 0 :(得分:0)
我想通了,我只需要像这样设置Values属性:
internal void InsertStrings(List<Tuple<string, string>> strings, Excel.Range selection, ComObjectManager com)
{
const int singleRowCell = 1;
const int columnsToArea = 2;
int firstRow = selection.Row;
int column = selection.Column;
for (int i = 0, j = firstRow; i < strings.Count; )
{
selection = com.Get<Excel.Range>(() => app.Cells[j, column]);
var mergeArea = com.Get<Excel.Range>(() => selection.MergeArea);
var mergeAreaRows = com.Get<Excel.Range>(() => mergeArea.Rows);
var cells = com.Get<Excel.Range>(() => app.Cells);
if (selection.MergeCells && mergeAreaRows.Count > singleRowCell)
{
var roomNameCell = com.Get<Excel.Range>(() => cells[j, column]);
var areaCell = com.Get<Excel.Range>(() => cells[j, column + columnsToArea]);
roomNameCell.Value = strings[i].Item1;
areaCell.Value = strings[i].Item2;
++i;
}
j += mergeAreaRows.Count;
}
}