匯出時使用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中文網其他相關文章!