导出工作表数据时自动重命名重复列
Contents
[
Hide
]
可能的使用场景
有时,用户在将工作表中的数据导出到数据表时会遇到重复列的问题。 DataTable 不能有重复的列,因此必须先重命名重复的列,然后才能将工作表数据导出到数据表中。 Aspose.Cells 可以根据您指定的策略自动重命名重复的列ExportTableOptions.RenameStrategy财产。如果您指定重命名策略.Digit,列将被重命名为 column1、column2、column3 等,如果您指定重命名策略.Letter,然后列将被重命名为columnA,columnB,columnC等。
导出工作表数据时自动重命名重复列
以下示例代码在工作表的前三列中添加了一些数据,但所有列都具有相同的名称,即人们.然后通过指定将工作表中的数据导出到数据表中重命名策略.信策略。然后它打印由 Aspose.Cells 生成的数据表的列名称。下面的屏幕截图显示了可视化工具中导出数据的数据表。如您所见,重复的列已重命名为 PeopleA、PeopleB 等。
示例代码
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-.NET | |
//Create a workbook. | |
Workbook wb = new Workbook(); | |
//Access first worksheet. | |
Worksheet ws = wb.Worksheets[0]; | |
//Write the same column name in columns A, B and C. | |
string columnName = "People"; | |
ws.Cells["A1"].PutValue(columnName); | |
ws.Cells["B1"].PutValue(columnName); | |
ws.Cells["C1"].PutValue(columnName); | |
//Insert data in column A, B and C. | |
ws.Cells["A2"].PutValue("Data"); | |
ws.Cells["B2"].PutValue("Data"); | |
ws.Cells["C2"].PutValue("Data"); | |
//Create ExportTableOptions and specify that you want to rename | |
//duplicate column names automatically via RenameStrategy property. | |
ExportTableOptions opts = new ExportTableOptions(); | |
opts.ExportColumnName = true; | |
opts.RenameStrategy = RenameStrategy.Letter; | |
//Export data to data table, duplicate column names will be renamed automatically. | |
System.Data.DataTable dataTable = ws.Cells.ExportDataTable(0, 0, 4, 3, opts); | |
//Now print the column names of the data table generated by Aspose.Cells while exporting worksheet data. | |
for (int i = 0; i < dataTable.Columns.Count; i++) | |
{ | |
Console.WriteLine(dataTable.Columns[i].ColumnName); | |
} | |
控制台输出
以下是上述示例代码的控制台输出,供参考。
People
PeopleA
PeopleB