问题
I've noticed some unexpected behavior in the table object when using Excel Javascript. To demo the problem, I've slightly modified some code that came with the ScriptLab example which shows how to add columns and rows to a table. The code below comes from that example with the exception that I've added the line of code "expensesTable.showHeaders = false;" and I've commented out the line of code "expensesTable.GetHeaderRowRange() ...". The rest is identical.
/** Create a new table with sample data */
async function setup() {
await Excel.run(async (context) => {
context.workbook.worksheets.getItemOrNullObject("Sample").delete();
const sheet = context.workbook.worksheets.add("Sample");
const expensesTable = sheet.tables.add("A1:D1", false /*hasHeaders*/);
expensesTable.name = "ExpensesTable";
expensesTable.showHeaders = false; //only new line
//expensesTable.getHeaderRowRange().values = [["Date", "Merchant", "Category", "Amount"]];
expensesTable.rows.add(null /*add at the end*/, [
["1/1/2017", "The Phone Company", "Communications", "$120"],
["1/2/2017", "Northwind Electric Cars", "Transportation", "$142"],
["1/5/2017", "Best For You Organics Company", "Groceries", "$27"],
["1/10/2017", "Coho Vineyard", "Restaurant", "$33"],
["1/11/2017", "Bellows College", "Education", "$350"],
["1/15/2017", "Trey Research", "Other", "$135"],
["1/15/2017", "Best For You Organics Company", "Groceries", "$97"]
]);
sheet.getUsedRange().format.autofitColumns();
sheet.getUsedRange().format.autofitRows();
sheet.activate();
await context.sync();
});
}
When you run this, the result looks like this ...
Note that the table is now defined as the range A9:D9. If you select the named range "expenseTable" in the upper left corner ...
It selects rows A9:D9. I would have expected the table to be in cells A1:D8.
However, if you remove the line "expensesTable.showHeaders = false;" Now the table is the range A1:D8 (as I would have expected). You end up with this ...
Is this a bug or am I missing something?
Update
I'm using Excel version 1907 (Build 11901.20080) which pushed on July 15th. https://www.tenforums.com/windows-10-news/136720-office-insider-monthly-targeted-v1907-build-11901-20080-july-15-a.html
Before that, I don't believe (but not 100% sure) this behavior existed. Another update, I found a PC in our office with Excel version 1906, it did not exhibit the same behavior.
来源:https://stackoverflow.com/questions/57169164/showheaders-false-results-in-unexpected-table-range-using-javascript