问题
I am new to VSTO and am encountering an issue I can't seem to figure out. I am trying to display a simple table in Excel 2013 and everything populates, except the column display names come out to be "Column1, Column2, Column3".
Here is my code:
var worksheet = Globals.Sheet1;
worksheet.Cells.Clear();
var table = new DataTable("Users");
// Set Columns
var columns = new List<DataColumn>
{
new DataColumn("Staged") { ColumnName = "Staged", Caption = "Staged"},
new DataColumn("FirstName") { ColumnName = "First Name", Caption = "First Name" },
new DataColumn("LastName") { ColumnName = "Last Name", Caption = "Last Name"}
};
foreach (var column in columns)
{
table.Columns.Add(column);
}
var lastFilledRow = 1;
// Populate data
for (var i = 1; i < 11; i++)
{
var row = table.NewRow();
row[table.Columns[0]] = "";
row[table.Columns[1]] = "Joesph " + i;
row[table.Columns[2]] = "Bellow " + i;
table.Rows.Add(row);
lastFilledRow++;
}
var lastCell = "C" + lastFilledRow;
worksheet.Controls.Remove("userList");
var list = worksheet.Controls.AddListObject(worksheet.Range["A1", lastCell], "userList");
list.SetDataBinding(table);
Stepping through the code in debug mode, all the way through the code I cannot see any attributes set to "Column1", but they are set to the values provided. I know these are the default values for ColumnName.
My question is, Why are the ColumnNames printing out in excel as Column1, Column2, Column3 when I'm explictly setting the values for ColumnName?
回答1:
You need to name the columns explicitly. After var list = ...
add the following:
list.ListColumns[1].Name = "Staged";
list.ListColumns[2].Name = "First Name";
list.ListColumns[3].Name = "Last Name";
来源:https://stackoverflow.com/questions/38773323/datatable-datacolumn-columnname-not-displaying