從 C# 匯出時如何將 Excel 欄位格式化為小數?
Jan 07, 2025 pm 12:03 PM從C 匯出時將Excel 欄位格式化為十進位
要在從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中文網其他相關文章!
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn

熱門文章
擊敗分裂小說需要多長時間?
3 週前
By DDD
倉庫:如何復興隊友
3 週前
By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island冒險:如何獲得巨型種子
3 週前
By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.能量晶體解釋及其做什麼(黃色晶體)
1 週前
By 尊渡假赌尊渡假赌尊渡假赌
公眾號網頁更新緩存難題:如何避免版本更新後舊緩存影響用戶體驗?
3 週前
By 王林

熱門文章
擊敗分裂小說需要多長時間?
3 週前
By DDD
倉庫:如何復興隊友
3 週前
By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island冒險:如何獲得巨型種子
3 週前
By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.能量晶體解釋及其做什麼(黃色晶體)
1 週前
By 尊渡假赌尊渡假赌尊渡假赌
公眾號網頁更新緩存難題:如何避免版本更新後舊緩存影響用戶體驗?
3 週前
By 王林

熱門文章標籤

記事本++7.3.1
好用且免費的程式碼編輯器

SublimeText3漢化版
中文版,非常好用

禪工作室 13.0.1
強大的PHP整合開發環境

Dreamweaver CS6
視覺化網頁開發工具

SublimeText3 Mac版
神級程式碼編輯軟體(SublimeText3)