2017-02-08 15 views
1

Я просто хотел бы установить строку для заголовка моего документа excel перед столбцами. Кто-нибудь может мне помочь?! Следуйте код:Как установить строку перед столбцами при генерации Excel (xlsx)

Здесь я создаю мой формат Excel, с колоннами

DataTable dt = new DataTable(); 

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

И вот после того, как уже определили свои ценности (вар value1 = "Exemple")

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

Вы можете добавить первые два столбца: первый один с названием, второй с пробелом (потому что, если установить опустошить имя столбца будет 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

Я думаю, что проще всего сделать было бы написать в заголовке информацию в файл Excel, закройте его, а затем открыть его снова добавьте фактический файл данных в файл Excel. An example implementation can be found in this answer.

В качестве примечания, убедитесь, что вы используете FileStream, а не MemoryStream, чтобы ваши изменения были сохранены.