在导出时使用 C# 将 Excel 列格式设置为十进制
使用 C# 将数据从数据库导出到 Excel 时,可能会遇到问题数字列的格式不正确。特别是,小数值可能会显示为整数,而不是显示小数位。
要解决此问题并确保正确导出小数列,您可以使用以下方法将小数格式添加到Excel 文件:
private static void ExportToExcel(DataTable dt, string FileName) { // Create an ExcelPackage object. using (ExcelPackage excelPackage = new ExcelPackage()) { // Add a new worksheet to the package. ExcelWorksheet ws = excelPackage.Workbook.Worksheets.Add(FileName); // Load the data from the DataTable into the worksheet. ws.Cells["A1"].LoadFromDataTable(dt, true); // Autofit the columns to accommodate the data. ws.Cells[ws.Dimension.Address].AutoFitColumns(); // Iterate through the columns and apply decimal formatting to the desired ones. for (int col = 1; col <= ws.Dimension.End.Column; col++) { // Get the cell in the first row (header row) of the column. var cell = ws.Cells[1, col]; // If the column contains numeric data, apply decimal formatting to it. var columnType = dt.Columns[col - 1].DataType; if (columnType == typeof(decimal) || columnType == typeof(double)) { // Set the number format to two decimal places. cell.Style.Numberformat.Format = "0.00"; } } // Convert the ExcelPackage object to a byte array. byte[] bin = excelPackage.GetAsByteArray(); // Send the byte array to the browser for download. Response.ClearHeaders(); Response.Clear(); Response.Buffer = true; Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; Response.AddHeader("content-length", bin.Length.ToString()); Response.AddHeader("content-disposition", "attachment; filename=\"" + FileName + ".xlsx\""); Response.OutputStream.Write(bin, 0, bin.Length); Response.Flush(); // Complete the request and clean up. HttpContext.Current.ApplicationInstance.CompleteRequest(); } }
此方法接受 DataTable 和文件名作为参数。它创建一个 ExcelPackage 对象并将数据加载到其中。然后,代码迭代每一列并检查它是否包含数字数据。如果是,则数字格式设置为“0.00”以确保显示两位小数。最后,ExcelPackage被转换为字节数组并作为附件发送到浏览器。
以上是使用C#导出数据时如何正确格式化Excel小数列?的详细内容。更多信息请关注PHP中文网其他相关文章!