gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 23:03:40 24 4
gpt4 key购买 nike

我只想在列之前为我的 excel 文档的标题设置一行。有人能帮我吗?!按照代码:

这里我创建了我的 excel 格式,带有列

DataTable dt = new DataTable();

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

这里已经定义了我的值 (var 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();
}}

最佳答案

您可以添加前两列:第一列带有标题,第二列带有空格字符(因为如果设置为空,列名将为 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 方法中进行。

关于c# - 生成Excel(xlsx)时如何在列之前设置一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42115640/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com