注意:我为 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 对象将数据导入现有模板文件,其中包含占位符data markers 以指示应将数据导入到何处。
ExcelTemplate 还有DataBindingProperties,它控制在调用ExcelTemplate.BindData 时如何导入数据。其中一个属性DataBindingProperties.Transpose 将旋转数据。此属性仅在数据源为二维数组时生效。
//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 不导入列名。要转置和导入列名,您需要一个 separate data marker in the template(即 %%=$HeaderNames)并单独调用 ExcelTemplate.BindColumnData 以将标题名称导入列中。
//headerNames is of type object[]
//dataBindProps2 is a second DataBindingProperties that is not set to transpose
xlt.BindColumnData(headerNames, "HeaderNames", dataBindProps2);