簡體   English   中英

如何使用C#將.xlsx文件轉換為.xlsx,然后使用epplus編輯.xlsx文件,例如為單元格着色

[英]How do I convert .xls file to .xlsx using c# and then edit the .xlsx file like coloring cells using epplus

我編寫了將.xls轉換為.xlsx的程序,該程序更改了擴展名,但是epplus函數無法正常運行轉換后的文件。 下面是將.xls轉換為.xlsx並為.xlsx文件的單元格着色的代碼,該程序正在運行,沒有任何錯誤或異常,但是在運行該程序后,excel並未使用顏色進行編輯

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Drawing;
using OfficeOpenXml;
using OfficeOpenXml.Style;

namespace Project42
{
class Class1
{
    static void Main(string[] args)
    {
        Console.WriteLine("File Extension Conversion From .xls to .xlsx");
        try
        {

            string filePath = @"C:\Users\mvmurthy\Desktop\abc.xls";
            if (filePath.EndsWith(".xls"))
            {
                File.Move(filePath, Path.ChangeExtension(filePath, ".xlsx"));
                Console.WriteLine("File Extension Updated To .xlsx");

            }
                FileInfo newFile = new FileInfo(@"C:\Users\mvmurthy\Downloads\abc.xlsx");
                ExcelPackage pck = new ExcelPackage(newFile);
                var ws = pck.Workbook.Worksheets["Contents"];
                ws.Cells["K:K"].Style.Fill.PatternType = ExcelFillStyle.Solid;
                ws.Cells["K:K"].Style.Fill.BackgroundColor.SetColor(Color.Yellow);
                ws.Cells["M:M"].Style.Fill.PatternType = ExcelFillStyle.Solid;
                ws.Cells["M:M"].Style.Fill.BackgroundColor.SetColor(Color.Yellow);
                ws.Cells["O:O"].Style.Fill.PatternType = ExcelFillStyle.Solid;
                ws.Cells["O:O"].Style.Fill.BackgroundColor.SetColor(Color.Yellow);
                pck.Save();


        }
        catch (Exception)
        {
            Console.WriteLine("File Extension Cannot Be Changed...Try again...");
        }
    }
}
}

您不能僅更改文件擴展名,就可以使用辦公自動化將其重新保存為.xlsx。 如果數據足夠簡單,則可以先使用Office Automation或其他支持.xls的庫讀取數據,然后使用epplus ..編寫.xlsx,然后再以.xlsx格式工作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM