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

问题描述:

我编写了将.xls转换为.xlsx的程序,但程序更改了扩展名,但epplus函数不工作转换文件。下面是转换的.xls原来的.xlsx和颜色,程序没有任何错误或异常运行的.xlsx文件细胞的代码,但Excel是没有得到与颜色运行程序如何使用c#将.xls文件转换为.xlsx,然后使用epplus编辑.xlsx文件,如使用epplus着色单元格

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

你能给我们进一步的信息吗?有抛出异常,还是只是不工作?如果发生异常,请提供。 –

+0

@StefanKert:在运行上述程序后打开excel时,没有例外,excel没有被编辑(excel中没有值) – manvitha

+2

更改扩展名是错误的。你必须保存为xlsx,文件内部不同。 –

编后

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