上面问题中List赋值部分,代码写法有点问题,修改了一下,下面是整个方法,加截图。
private void button1_Click(object sender, EventArgs e)
{
XSSFWorkbook workBook = new XSSFWorkbook(); //实例化XSSF
XSSFSheet sheet = (XSSFSheet)workBook.CreateSheet(); //创建一个sheet
List<List<string>> res = new List<List<string>>();
res.Add(new List<string>() { "0", "1", "2", "3", "4", "5", "6","7", "8","9", "10" });
res.Add(new List<string>() { "0", "1", "2", "3" });
res.Add(new List<string>() { "0", "1", "2" });
//需要创建的第几行
int rowIndex = -1;
for (int i = 0; i < res.Count; i++)
{
rowIndex++;
IRow rw = sheet.CreateRow(rowIndex);
int count = (int)res[i].Count;
for (int j = 0; j < res[i].Count;j++)
{
//计算j在第几行
var rowNumber = (int)j/3;
if (rowNumber==0)
{
//循环length次,赋值。
var length = res[i].Count<3 ? res[i].Count : 3;
for (int n = 0; n < length; n++)
{
rw.CreateCell(0).SetCellValue("NET" + (i + 1).ToString());
rw.CreateCell(1).SetCellValue("sub0");
ICell ce = rw.CreateCell(n + 2);
ce.SetCellValue(res[i][n].ToString());
}
//跳过length个值
j+=(length-1);
}
else
{
//新增加一行
rowIndex++;
int cellIndex = 0;
IRow rw1 = sheet.CreateRow(rowIndex);
for (int m=0; m < 3; m++)
{
//判断是否超过了总行数
if ((j+m)<count)
{
ICell ce1 = rw1.CreateCell(m+ 2);
ce1.SetCellValue(res[i][j+m].ToString());
cellIndex++;
}
else
{
break;
}
}
j+=cellIndex-1;
}
}
}
string saveFileName = "D:\\示例.xlsx";
try
{
using (FileStream fs = new FileStream(saveFileName, FileMode.Create, FileAccess.Write))
{
workBook.Write(fs); //写入文件
workBook.Close(); //关闭
}
MessageBox.Show("导出成功");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString());
workBook.Close();
}
}
执行后效果如下。
有用请采纳哦。