要在从 C# 导出时将 Excel 文件的特定列格式化为十进制,可以使用以下方法:
using OfficeOpenXml; using OfficeOpenXml.Style; using DataTable dt; public void ExportToExcel(DataTable dt, string FileName) { // Create a new Excel package. using (ExcelPackage excelPackage = new ExcelPackage()) { // Create a new worksheet and load the data from the DataTable into it. ExcelWorksheet ws = excelPackage.Workbook.Worksheets.Add(FileName); ws.Cells["A1"].LoadFromDataTable(dt, true); // Apply number formatting to the specified columns (Actual Estimated Price and Approved Estimated Price in this example). int[] decimalColumns = { 1, 2 }; foreach (int col in decimalColumns) { ws.Cells[ws.Dimension.Start.Row, col, ws.Dimension.End.Row, col].Style.Numberformat.Format = "0.00"; } // Other formatting and cleanup code as needed... // Convert the Excel package to a byte array and send it to the browser. byte[] bin = excelPackage.GetAsByteArray(); // ... } }
除了小数格式之外,您还可以使用 OfficeOpenXML 库合并标题单元格并设置其他格式选项。上面的代码示例演示了如何执行这些操作,例如合并 CustomerName 标题单元格并将标题行设置为灰色并带有粗体文本:
const int headerRow = 1; ws.Cells[headerRow, 1, headerRow, 2].Merge = true; ws.Cells[headerRow, 1].Value = "CustomerName"; // ... for (int col = 1; col <= ws.Dimension.End.Column; col++) { // Make all columns just a bit wider. ws.Column(col).Width = ws.Column(col).Width + 1; var cell = ws.Cells[headerRow, col]; // Format the header cells cell.Style.Font.Bold = true; cell.Style.Fill.PatternType = ExcelFillStyle.Solid; cell.Style.Fill.BackgroundColor.SetColor(ColorTranslator.FromHtml("#BFBFBF")); }
通过这些自定义,导出的 Excel 文件将具有所需的内容小数列和标题单元格的格式。
以上是从 C# 导出时如何将 Excel 列格式化为小数?的详细内容。更多信息请关注PHP中文网其他相关文章!