c#-nopi设置excel内容

public string Imp(DataSet ds, string title)
{
    string directory = $"UploadFiles/ExportExcel/{DateTime.Now.ToString("yyyy/MM/dd", System.Globalization.DateTimeFormatInfo.InvariantInfo)}";
    if (!Directory.Exists($"./wwwroot/{directory}"))
    {
        Directory.CreateDirectory($"./wwwroot/{directory}");
    }
    string name = $"{title}.xlsx";
    string url = $"{directory}/{name}";
    //生成文件存放路径
    string filePath = $@"./wwwroot/{url}";
    if (File.Exists(filePath))
    {
        File.Delete(filePath);
    }

    using FileStream file = new FileStream(filePath, FileMode.Create, FileAccess.Write);
    if (ds != null)
    {
        foreach (DataTable item in ds.Tables)
        {
            if (item != null && item.Rows.Count > 0)
            {
                var workbook = new XSSFWorkbook();
                ICellStyle headStyle = workbook.CreateCellStyle(); //头样式
                headStyle.VerticalAlignment = VerticalAlignment.Center;
                headStyle.Alignment = HorizontalAlignment.Center;
                XSSFFont font = workbook.CreateFont() as XSSFFont;
                font.FontHeightInPoints = 10;
                font.IsBold = true;
                headStyle.SetFont(font);

                ICellStyle bodyStyle = workbook.CreateCellStyle(); //body样式
                bodyStyle.VerticalAlignment = VerticalAlignment.Center;
                bodyStyle.Alignment = HorizontalAlignment.Center;

                ISheet sheet = workbook.CreateSheet(item.TableName);
                int rowCount = item.Rows.Count; //行数
                int columnCount = item.Columns.Count; //列数

                //设置列头
                IRow rowHead = sheet.CreateRow(0); //excel第一行设为列头
                rowHead.HeightInPoints = 22;
                for (int c = 0; c < columnCount; c++)
                {
                    var cell = rowHead.CreateCell(c);
                    cell.SetCellValue(item.Columns[c].ColumnName);
                    cell.CellStyle = headStyle;
                    sheet.SetColumnWidth(c, 14 * 256);
                }
                //设置每行每列的单元格,
                for (int i = 0; i < rowCount; i++)
                {
                    IRow rowBody = sheet.CreateRow(i + 1);
                    rowBody.HeightInPoints = 20;
                    for (int j = 0; j < columnCount; j++)
                    {
                        var cell = rowBody.CreateCell(j); //excel第二行开始写入数据
                        cell.SetCellValue(item.Rows[i][j].ToString());
                        cell.CellStyle = bodyStyle;
                    }
                }
                workbook.Write(file);
            }
            else
            {
                throw new FLCException("错误");
            }
        }
    }
    return url;
}
posted @ 2025-08-04 13:45  Yichen_liuuil  阅读(7)  评论(0)    收藏  举报