简体   繁体   中英

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

I wrote program to convert .xls to .xlsx, the program changes the extension but epplus functions are not working the converted file. below is the code to convert .xls to .xlsx and color the cells of .xlsx file, the program is running without any errors or exception, but the excel is not getting edited with the colors after running the program

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...");
        }
    }
}
}

You cant just change the file extension, you may be able to use office automation to resave as .xlsx. if the data is simple enough you can just first read the data using office automation or other library that supports .xls, then write the .xlsx using epplus.. which will then work on the .xlsx format.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM