To format specific columns of an Excel file as decimal when exporting from C#, you can use the following method:
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(); // ... } }
In addition to the decimal formatting, you can also merge header cells and set other formatting options using the OfficeOpenXML library. The code sample above demonstrates how to do these operations, such as merging the CustomerName header cells and setting the header row to gray with bold text:
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")); }
With these customizations, your exported Excel file will have the desired formatting for both decimal columns and header cells.
The above is the detailed content of How to Format Excel Columns as Decimals When Exporting from C#?. For more information, please follow other related articles on the PHP Chinese website!