如何使用c#将.xls文件转换为.xlsx文件,然后像使用epplus为单元格着色一样编辑.xlsx文件?

本文关键字:文件 xlsx 单元格 编辑 一样 epplus xls 何使用 转换 后像 然后 | 更新日期: 2023-09-27 18:03:15

我写了一个程序来转换。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...");
        }
    }
}
}

如何使用c#将.xls文件转换为.xlsx文件,然后像使用epplus为单元格着色一样编辑.xlsx文件?

您不能只是更改文件扩展名,您可以使用办公自动化将其保存为。xlsx。如果数据足够简单,您可以先使用office自动化或其他支持.xls的库读取数据,然后使用epplus编写.xlsx。这将在。xlsx格式下工作。