我正在寻找一种方法来检索在Excel工作表中创建的某种表对象,然后对其进行操作。
我试过这样的事情:
Excel.Worksheet activeWorksheet = (Excel.Worksheet)Globals.ThisAddIn.Application.ActiveSheet;
foreach (var sheetObject in activeWorksheet.ListObjects)
{
if ((sheetObject as Excel.TableObject) != null)
{
var table = (Excel.TableObject)sheetObject;
}
if ((sheetObject as Excel.DataTable) != null)
{
var table = (Excel.DataTable)sheetObject;
}
if ((sheetObject as Excel.PivotTable) != null)
{
var table = (Excel.PivotTable)sheetObject;
}
if ((sheetObject as Excel.ModelTable) != null)
{
var table = (Excel.ModelTable)sheetObject;
}
if ((sheetObject as Excel.QueryTables) != null)
{
var table = (Excel.QueryTables)sheetObject;
}
}
不幸的是,这个演员阵容中的任何一个都返回null然后返回null。 你知道在C#中检索这样的表可能有其他方法吗?
答案 0 :(得分:0)
可能是Range?
来自:http://www.dotnetperls.com/excel
Range excelRange = sheet.UsedRange;
object[,] valueArray = (object[,])excelRange.get_Value(
XlRangeValueDataType.xlRangeValueDefault);
https://msdn.microsoft.com/en-us/library/microsoft.office.interop.excel.range_members(v=vs.15).aspx
答案 1 :(得分:0)
要仅对工作表中创建的表格进行处理,我使用了以前答案中建议的“范围”:
Excel.Worksheet activeWorksheet = (Excel.Worksheet)Globals.ThisAddIn.Application.ActiveSheet;
foreach (Excel.ListObject table in activeWorksheet.ListObjects)
{
Excel.Range tableRange = table.Range;
String[] dataInRows = new string[tableRange.Rows.Count];
int i = 0;
foreach (Excel.Range row in tableRange.Rows)
{
for (int j = 0; j < row.Columns.Count; j++)
{
if (row.Cells[1, j + 1].Value2 != null)
{
dataInRows[i] = dataInRows[i] + "_" + row.Cells[1, j + 1].Value2.ToString();
}
}
i++;
}
}