首頁 >後端開發 >C++ >從 C# 匯出時如何將 Excel 欄位格式化為小數?

從 C# 匯出時如何將 Excel 欄位格式化為小數?

Susan Sarandon
Susan Sarandon原創
2025-01-07 12:03:41260瀏覽

How to Format Excel Columns as Decimals When Exporting from C#?

從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