EKsumic's Blog

let today = new Beginning();

Click the left button to use the catalog.

OR

C# 使用 EPPlus 复制 Excel 文件的内容、样式及合并单元格

在開發過程中,我們經常需要處理 Excel 文件,例如讀取、覆制或創建新的 Excel 文件。在本篇博客中,我將解釋如何使用 EPPlus 庫來覆制 Excel 文件的內容、樣式以及合並的單元格,並生成一個新的 Excel 文件。代碼中通過讀取模板文件,並將其內容和樣式覆制到一個新的 Excel 文件中,最後將生成的文件保存到指定目錄。

 

完整代码:

public partial class frmMain : Form
{
    public frmMain()
    {
        InitializeComponent();
    }

    private void btnReadExcel_Click(object sender, EventArgs e)
    {
        string templatePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "SampleData", "1入力補助表(様式1)新規.xlsx");
        string outputFolder = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "OutputFiles"); // 專門存放output的文件夾
        string outputPath = Path.Combine(outputFolder, "output.xlsx");

        // 創建output文件夾(如果不存在)
        if (!Directory.Exists(outputFolder))
        {
            Directory.CreateDirectory(outputFolder);
        }

        if (File.Exists(templatePath))
        {
            try
            {
                ExcelPackage.LicenseContext = LicenseContext.NonCommercial; // 設置EPPlus的授權上下文
                using (var package = new ExcelPackage(new FileInfo(templatePath)))
                {
                    var worksheet = package.Workbook.Worksheets[0];
                    // 新建一個Excel包
                    using (var newPackage = new ExcelPackage())
                    {
                        var newWorksheet = newPackage.Workbook.Worksheets.Add("様式1"); // 直接將工作表命名為【様式1】

                        // 設置列寬和行高
                        for (int col = 1; col <= 30; col++) // AD is column 30
                        {
                            newWorksheet.Column(col).Width = worksheet.Column(col).Width;
                        }

                        for (int row = 1; row <= 16; row++)
                        {
                            newWorksheet.Row(row).Height = worksheet.Row(row).Height;
                        }

                        // 複製單元格內容、樣式和合併的單元格
                        for (int row = 1; row <= 16; row++)
                        {
                            for (int col = 1; col <= 30; col++)
                            {
                                var cell = worksheet.Cells[row, col];
                                var value = cell.Text;

                                // 複製內容(如果有值)
                                if (!string.IsNullOrEmpty(value))
                                {
                                    newWorksheet.Cells[row, col].Value = value;
                                }

                                // 無論是否有值,都複製樣式和邊框
                                var originalStyle = cell.Style;
                                newWorksheet.Cells[row, col].Style.Font.Bold = originalStyle.Font.Bold;
                                newWorksheet.Cells[row, col].Style.Font.Italic = originalStyle.Font.Italic;
                                newWorksheet.Cells[row, col].Style.Font.UnderLine = originalStyle.Font.UnderLine;
                                newWorksheet.Cells[row, col].Style.Font.Size = originalStyle.Font.Size;

                                // 複製背景顏色,將 Rgb 轉換為 Color 類型
                                if (!string.IsNullOrEmpty(originalStyle.Fill.BackgroundColor.Rgb))
                                {
                                    Color bgColor = ColorTranslator.FromHtml("#" + originalStyle.Fill.BackgroundColor.Rgb);
                                    newWorksheet.Cells[row, col].Style.Fill.BackgroundColor.SetColor(bgColor);
                                }

                                // 複製邊框,無論單元格是否有值
                                var border = cell.Style.Border;
                                newWorksheet.Cells[row, col].Style.Border.Top.Style = border.Top.Style;
                                newWorksheet.Cells[row, col].Style.Border.Bottom.Style = border.Bottom.Style;
                                newWorksheet.Cells[row, col].Style.Border.Left.Style = border.Left.Style;
                                newWorksheet.Cells[row, col].Style.Border.Right.Style = border.Right.Style;

                                // 複製文字方向
                                newWorksheet.Cells[row, col].Style.TextRotation = originalStyle.TextRotation;

                                // 複製自動換行屬性
                                newWorksheet.Cells[row, col].Style.WrapText = originalStyle.WrapText;

                                // 複製對齊方式
                                newWorksheet.Cells[row, col].Style.HorizontalAlignment = originalStyle.HorizontalAlignment;
                                newWorksheet.Cells[row, col].Style.VerticalAlignment = originalStyle.VerticalAlignment;

                                // 檢查是否有合併單元格
                                if (worksheet.MergedCells[row, col] != null)
                                {
                                    string mergedAddress = worksheet.MergedCells[row, col];
                                    newWorksheet.Cells[mergedAddress].Merge = true;

                                    // 合併單元格可能需要重新設置邊框,確保顯示正確
                                    var mergedCellBorder = worksheet.Cells[mergedAddress].Style.Border;
                                    newWorksheet.Cells[mergedAddress].Style.Border.Top.Style = mergedCellBorder.Top.Style;
                                    newWorksheet.Cells[mergedAddress].Style.Border.Bottom.Style = mergedCellBorder.Bottom.Style;
                                    newWorksheet.Cells[mergedAddress].Style.Border.Left.Style = mergedCellBorder.Left.Style;
                                    newWorksheet.Cells[mergedAddress].Style.Border.Right.Style = mergedCellBorder.Right.Style;
                                }
                            }
                        }

                        // 保存新的 Excel 文件
                        FileInfo outputFile = new FileInfo(outputPath);
                        newPackage.SaveAs(outputFile);
                    }

                    MessageBox.Show($"Excel 內容已成功生成並保存到: {outputPath}");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error reading or writing Excel file: " + ex.Message);
            }
        }
        else
        {
            MessageBox.Show("Template file not found!");
        }
    }
}

 

代碼解釋

  1. 路徑設置:透過 AppDomain.CurrentDomain.BaseDirectory 獲取根目錄,並使用 Path.Combine 組合模板和輸出文件的路徑。如果輸出文件夾不存在,則自動創建。
  2. 讀取模板文件:使用 EPPlus 庫打開模板 Excel 文件,並創建一個新 Excel 文件,命名為 様式1。
  3. 複製內容與樣式:遍歷每個單元格,複製其內容、字體、背景顏色、邊框、對齊方式等,即使單元格為空,樣式也會被複製。還會檢查並複製合併單元格。
  4. 保存新文件:將生成的 Excel 文件保存至指定目錄,並透過彈出消息提示用戶。如果操作失敗,會顯示錯誤訊息。

這些要點展示了如何使用 EPPlus 庫高效處理 Excel 文件的複製,包括內容、樣式和合併單元格。

This article was last edited at 2024-10-22 10:10:39

Today's comments have reached the limit. If you want to comment, please wait until tomorrow (UTC-Time).

There is 14h20m47s left until you can comment.