ワークシートからデータをエクスポートする際に重複する列を自動的にリネーム
可能な使用シナリオ
ユーザーは、ワークシートからデータをデータテーブルにエクスポートする際に重複する列の問題に直面することがあります。データテーブルには重複する列を持つことはできないため、ワークシートデータをデータテーブルにエクスポートする前に重複列をリネームする必要があります。Aspose.Cells では、ExportTableOptions.RenameStrategyプロパティを使用して、指定された戦略に従って重複列を自動的にリネームできます。RenameStrategy.Digitを指定すると列名がcolumn1、column2、column3などのようにリネームされ、RenameStrategy.Letterを指定するとcolumnA、columnB、columnCなどのようにリネームされます。
ワークシートデータをエクスポートする際に重複する列の名前を自動的に変更する
次のサンプルコードでは、ワークシートの最初の3列にいくつかのデータを追加しますが、すべての列の名前がPeopleです。次に、RenameStrategy.Letter戦略を指定してワークシートからデータをデータテーブルにエクスポートします。その後、Aspose.Cells によって生成されたデータテーブルの列名を印刷します。次のスクリーンショットは、ビジュアライザ内でエクスポートされたデータを持つデータテーブルを示しています。重複する列がPeopleA、PeopleBなどにリネームされていることがわかります。
サンプルコード
// 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