注: 私は、OfficeWriter のメーカーである SoftArtisans で働いています。
データに一意の値があり、データを転置するだけでよい場合は、いくつかのオプションがあります。
たとえば、データが次のようになっているとします。
Date Name Address Age
05/01/2013 Bob 70 Random Dr 54
05/02/2013 Carl 50 Unique Rd 76
05/03/2013 Fred 432 Tiger Lane 56
05/04/2013 Amy 123 Think Ave 23
05/05/2013 Dana 58 Turtle Path 67
そして、次のようになるようにデータをインポートします。
Date 05/01/2013 05/02/2013 05/03/2013 05/04/2013 05/05/2013
Name Bob Carl Fred Amy Dana
Address 70 Random Dr 50 Unique Rd 432 Tiger Lane 123 Think Ave 58 Turtle Path
Age 54 76 56 23 67
最も簡単なオプション - ExcelApplication でインポート
最も簡単なオプションは、ExcelApplicationオブジェクトのWorksheet.ImportDataメソッドを使用して、プログラムでデータをインポートすることです。データのインポート方法をカスタマイズするには、いくつかのDataImportPropertiesを設定する必要があります。
//Open or create a file with ExcelApplication
ExcelApplication xla = new ExcelApplication();
Workbook wb = xla.Create(ExcelApplication.FileFormat.Xlsx);
//Get a handle on the worksheet where you want to import the data
//You can also create a new worksheet instead
Worksheet ws = wb.Worksheets.CreateWorksheet("ImportedData");
//Create a DataImportProperties object
//Set the data import to transpose the data
DataImportProperties dataImportProps = wb.CreateDataImportProperties();
dataImportProps.Transpose = true;
//Import the data
DataTable dt = GetData(); //random method that returns some data
ws.ImportData(dt, ws.Cells["A1"], dataImportProps);
//Stream the output back to the client
xla.Save(wb, Page.Response, "Output.xlsx", false);
ImportDataは、データ セットのヘッダー名を自動的にインポートしません。そのため、 DataImportProperties.UseColumnNamesをTRUEに設定して、ヘッダー名 (日付、名前、住所、年齢) をインポートすることもできます。
年齢や日付などの数値データをインポートする場合は、DataImportProperties.ConvertStringsをTRUEに設定して、それらがテキストではなく数値としてインポートされるようにすることもできます。
別の方法 - ExcelTemplate でインポート
別の方法は、ExcelTemplateオブジェクトを使用して、データをインポートする場所を示すプレースホルダーデータ マーカーを含む既存のテンプレート ファイルにデータをインポートすることです。
ExcelTemplate には、 ExcelTemplate.BindDataを呼び出すときにデータをインポートする方法を制御するDataBindingPropertiesもあります。プロパティの 1 つであるDataBindingProperties.Transposeは、データをピボットします。このプロパティは、データ ソースが 2 次元配列の場合にのみ有効です。
//Open a template with placeholder data markers
ExcelTemplate xlt = new ExcelTemplate();
xlt.Open("template.xlsx");
//Create DataBindingProperties and set it to transpose the data
DataBindingProperties dataBindProps = xlt.CreateDataBindingProperties();
dataBindProps.Transpose = true;
//Bind data to the template
//data is of type object[][]
//colNames is of type string[] e.g {"Date", "Name", "Address", "Age"}
xlt.BindData(data, colNames, "DataSource", dataBindProps);
//Process and save the template
xlt.Process();
xlt.Save(Page.Response, "Output.xlsx", false);
デフォルトでは、ExcelTemplate は列名をインポートしません。列名を転置してインポートするには、テンプレートに個別のデータ マーカー(つまり %%=$HeaderNames) が必要であり、ExcelTemplate.BindColumnData を個別に呼び出してヘッダー名を列にインポートします。
//headerNames is of type object[]
//dataBindProps2 is a second DataBindingProperties that is not set to transpose
xlt.BindColumnData(headerNames, "HeaderNames", dataBindProps2);