我目前正在用 C# 开发一个 excel 插件,其中包含几种方法(表值函数),可供 excel 用户和程序员 (VBA) 使用。
如何编写一个方法,将新的 ListObject(excel 表)添加到给定的 excel 工作表,并将给定的 DataTable 绑定(bind)为数据源?类似于以下内容:
using Excel = Microsoft.Office.Interop.Excel;
...
[ClassInterface(ClassInterfaceType.AutoDual)]
public class TableFunctions {
...
public Excel.ListObject CreateListObject(Excel.Worksheet ws, string TableName, DataTable dt, string CellStr = "A1")
{
...
}
这种将 Worksheet 对象作为参数发送的方法显然行不通。或者可以吗?
最佳答案
经过一些研究,我找到了问题的答案,即如何在 C# 中以编程方式将 ListObject(excel 表)添加到工作表:
public Excel.ListObject WriteToExcelTable(Excel.Worksheet WSheet, string TableName, string CellStr = "A1", bool ClearSheetContent = false)
{
Excel.Range range;
if (ClearSheetContent)
WSheet.Cells.ClearContents(); // clear sheet content
// get upper left corner of range defined by CellStr
range = (Excel.Range)WSheet.get_Range(CellStr).Cells[1, 1]; //
// Write table to range
HelperFunc.WriteTableToExcelSheet(WSheet, this._tbl, range.Address);
// derive range for table, +1 row for table header
range = range.get_Resize(this.RowCount + 1, this.ColumnCount);
// add ListObject to sheet
// ListObjects.AddEx Method
// http://msdn.microsoft.com/en-us/library/microsoft.office.interop.excel.listobjects.addex%28v=office.14%29.aspx
Excel.ListObject tbl = (Excel.ListObject)WSheet.ListObjects.AddEx(
SourceType: Excel.XlListObjectSourceType.xlSrcRange,
Source: range,
XlListObjectHasHeaders: Excel.XlYesNoGuess.xlYes);
// set name of excel table
tbl.Name = TableName;
// return excel table (ListObject)
return (Excel.ListObject)tbl;
}
参见 my article关于此代码和其他用于 excel 和 .net 集成的相关代码。
关于c# - 如何将 excel ListObject 添加到 C# 中的给定工作表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25460922/