如何在生成Excel(xlsx)时在列之前设置一行

时间:2017-02-08 14:21:03

标签: c# asp.net excel xlsx npoi

我只想在列之前为我的Excel文档的标题设置一行。有人能帮我吗?!请遵循以下代码:

在这里,我使用列

创建我的excel格式
DataTable dt = new DataTable();

dt.Columns.Add("Value 1", typeof(string));
dt.Columns.Add("Value 2", typeof(string));

此后已经定义了我的值(var value1 ="例如")

dt.Rows.Add(
value1,
value2);

WriteExcelWithNPOI(dt, "xlsx");

我希望这是可以理解的。

如有必要,还要遵循生成xlsx的代码:

public void WriteExcelWithNPOI(DataTable dt, String extension){

IWorkbook workbook;

if (extension == "xlsx")
{
    workbook = new XSSFWorkbook();
}
else if (extension == "xls")
{
    workbook = new HSSFWorkbook();
}
else
{
    throw new Exception("This format is not supported");
}

ISheet sheet1 = workbook.CreateSheet("Sheet 1");

//make a header row
IRow row1 = sheet1.CreateRow(0);

for (int j = 0; j < dt.Columns.Count; j++)
{
    ICell cell = row1.CreateCell(j);
    String columnName = dt.Columns[j].ToString();
    cell.SetCellValue(columnName);
}

//loops through data
for (int i = 0; i < dt.Rows.Count; i++)
{
    IRow row = sheet1.CreateRow(i + 1);
    for (int j = 0; j < dt.Columns.Count; j++)
    {

        ICell cell = row.CreateCell(j);
        String columnName = dt.Columns[j].ToString();
        cell.SetCellValue(dt.Rows[i][columnName].ToString());
    }
}

using (var exportData = new MemoryStream())
{
    Response.Clear();
    workbook.Write(exportData);
    if (extension == "xlsx") //xlsx file format
    {
        Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
        Response.AddHeader("Content-Disposition", string.Format("attachment;filename={0}", "Relatorio-Rotas.xlsx"));
        Response.BinaryWrite(exportData.ToArray());
    }
    else if (extension == "xls")  //xls file format
    {
        Response.ContentType = "application/vnd.ms-excel";
        Response.AddHeader("Content-Disposition", string.Format("attachment;filename={0}", "Relatorio-Rotas.xls"));
        Response.BinaryWrite(exportData.GetBuffer());
    }
    Response.End();
}}

public void WriteTsv<T>(IEnumerable<T> data, TextWriter output){

PropertyDescriptorCollection props = TypeDescriptor.GetProperties(typeof(T));
foreach (PropertyDescriptor prop in props)
{
    output.Write(prop.DisplayName); // header
    output.Write("\t");
}
output.WriteLine();
foreach (T item in data)
{
    foreach (PropertyDescriptor prop in props)
    {
        output.Write(prop.Converter.ConvertToString(
                prop.GetValue(item)));
        output.Write("\t");
    }
    output.WriteLine();
}}

2 个答案:

答案 0 :(得分:2)

您可以添加前两列:第一列带有标题,第二列带有空格字符(因为如果设置为空,列名称将为Column1):

DataTable dt = new DataTable();

dt.Columns.Add("Title", typeof(string));
dt.Columns.Add(" ", typeof(string));

dt.Rows.Add("Value 1", "Value 2");
dt.Rows.Add("Example 1", "Example 2");

WriteExcelWithNPOI(dt, "xlsx");

请注意,DataTable没有colspan属性,因此如果要合并列,则必须使用WriteExcelWithNPOI方法执行此操作。

答案 1 :(得分:1)

我认为最简单的方法是将标题信息写入Excel文件,关闭它,然后再次打开它以将实际数据表添加到Excel文件中。 An example implementation can be found in this answer.

请注意,请务必使用User-Agent而不是FileStream,以便保存更改。