使用NPOI从SQL生成Excel文件时打开报错(C#)
使用NPOI生成Excel文件时打开提示内容错误
我正在使用NPOI从SQL表生成Excel文件,代码执行一切正常,但打开生成的文件时出现内容错误提示(附错误截图)。
控制器代码
using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.Data.SqlClient; using Microsoft.EntityFrameworkCore; using NPOI.HSSF.UserModel; using NPOI.SS.UserModel; using NPOI.XSSF.UserModel; using System.Data; namespace SfApi.Controllers { [Route("api/[controller]")] [ApiController] public class SuccessfactorController : ControllerBase { private DataContext _context; private string sqlstring; public SuccessfactorController(DataContext context) { _context = context; //sqlstring will be use in each method in this controller with query sqlstring = _context.Database.GetConnectionString(); } [HttpGet("GetSfResults")] public async Task<ActionResult<List<Successfactor>>> Get() { DataTable ds = new DataTable(); using (SqlConnection con = new SqlConnection(sqlstring)) { string query = "SELECT * FROM test"; using (SqlCommand cmd = new SqlCommand(query)) { cmd.Connection = con; using (SqlDataAdapter sda = new SqlDataAdapter(cmd)) { sda.Fill(ds); } } } DataTable_To_Excel(ds, "D:\ExcelTest\ExcelTest.xlsx"); return Ok(_context.Successfactor); }
上述代码从SQL获取数据并填充到DataTable中。
DataTable转Excel方法代码
private void DataTable_To_Excel(DataTable pDatos, string pFilePath) { try { if (pDatos != null && pDatos.Rows.Count > 0) { IWorkbook workbook = null; ISheet worksheet = null; using (FileStream stream = new FileStream(pFilePath, FileMode.Create, FileAccess.Write)) { string Ext = System.IO.Path.GetExtension(pFilePath); //<- File extension switch (Ext.ToLower()) { case ".xls": HSSFWorkbook workbookH = new HSSFWorkbook(); NPOI.HPSF.DocumentSummaryInformation dsi = NPOI.HPSF.PropertySetFactory.CreateDocumentSummaryInformation(); dsi.Company = "Saskpolytech"; dsi.Manager = "Learning Technology"; workbookH.DocumentSummaryInformation = dsi; workbook = workbookH; break; case ".xlsx": workbook = new XSSFWorkbook(); break; } //worksheet = workbook.CreateSheet(pDatos.TableName); //<- Use table name as Sheet name worksheet = workbook.CreateSheet("testSheetName"); //<- Use table name as Sheet name //FORMATS FOR CERTAIN TYPES OF DATA ICellStyle _TextCellStyle = workbook.CreateCellStyle(); _TextCellStyle.DataFormat = workbook.CreateDataFormat().GetFormat("text"); ICellStyle _doubleCellStyle = workbook.CreateCellStyle(); _doubleCellStyle.DataFormat = workbook.CreateDataFormat().GetFormat("#,##0.###"); ICellStyle _intCellStyle = workbook.CreateCellStyle(); _intCellStyle.DataFormat = workbook.CreateDataFormat().GetFormat("#,##0"); ICellStyle _boolCellStyle = workbook.CreateCellStyle(); _boolCellStyle.DataFormat = workbook.CreateDataFormat().GetFormat("BOOLEAN"); ICellStyle _dateCellStyle = workbook.CreateCellStyle(); _dateCellStyle.DataFormat = workbook.CreateDataFormat().GetFormat("dd-MM-yyyy"); ICellStyle _dateTimeCellStyle = workbook.CreateCellStyle(); _dateTimeCellStyle.DataFormat = workbook.CreateDataFormat().GetFormat("dd-MM-yyyy HH:mm:ss"); //REAR IN THE FIRST ROW THE TITLES OF THE COLUMNS int iRow = 0; if (pDatos.Columns.Count > 0) { int iCol = 0; IRow fila = worksheet.CreateRow(iRow); foreach (DataColumn columna in pDatos.Columns) { ICell cell = fila.CreateCell(iCol, CellType.String); cell.SetCellValue(columna.ColumnName); cell.CellStyle = _TextCellStyle; iCol++; } iRow++; } //NOW CREATE A ROW FOR EACH RECORD IN THE TABLE foreach (DataRow row in pDatos.Rows) { IRow fila = worksheet.CreateRow(iRow); int iCol = 0; foreach (DataColumn column in pDatos.Columns) { ICell cell = null; //<-Represents the current cell object cellValue = row[iCol]; //<- The current value of the cell switch (column.DataType.ToString()) { case "System.Boolean": if (cellValue != DBNull.Value) { cell = fila.CreateCell(iCol, CellType.Boolean); if (Convert.ToBoolean(cellValue)) { cell.SetCellFormula("TRUE()"); } else { cell.SetCellFormula("FALSE()"); } cell.CellStyle = _boolCellStyle; } break; case "System.String": if (cellValue != DBNull.Value) { cell = fila.CreateCell(iCol, CellType.String); cell.SetCellValue (Convert.ToString(cellValue)); cell.CellStyle = _TextCellStyle; } break; case "System.Int32": if (cellValue != DBNull.Value) { cell = fila.CreateCell(iCol, CellType.Numeric); cell.SetCellValue(Convert.ToInt32(cellValue)); cell.CellStyle = _intCellStyle; } break; case "System.Int64": if (cellValue != DBNull.Value) { cell = fila.CreateCell(iCol, CellType.Numeric); cell.SetCellValue(Convert.ToInt64(cellValue)); cell.CellStyle = _intCellStyle; } break; case "System.Decimal": if (cellValue != DBNull.Value) { cell = fila.CreateCell(iCol, CellType.Numeric); cell.SetCellValue(Convert.ToDouble(cellValue)); cell.CellStyle = _doubleCellStyle; } break; case "System.Double": if (cellValue != DBNull.Value) { cell = fila.CreateCell(iCol, CellType.Numeric); cell.SetCellValue(Convert.ToDouble(cellValue)); cell.CellStyle = _doubleCellStyle; } break; case "System.DateTime": if (cellValue != DBNull.Value) { cell = fila.CreateCell(iCol, CellType.Numeric); cell.SetCellValue(Convert.ToDateTime(cellValue)); //If there is no Time value, use dd-MM-yyyy format DateTime cDate = Convert.ToDateTime(cellValue); if (cDate != null && cDate.Hour > 0) { cell.CellStyle = _dateTimeCellStyle; } else { cell.CellStyle = _dateCellStyle; } } break; default: break; } iCol++; } iRow++; } workbook.Write(stream); stream.Close(); } } } catch (Exception ex) { throw ex; } }
我花了大量时间寻找解决方案,但未在网上找到相关内容,希望能得到各位的指导。
内容的提问来源于stack exchange,提问作者Anis Khoja
相关产品推荐
相关产品推荐

