简体   繁体   English

将byte []从xls转换为xlsx文件并保存

[英]Convert byte[] from xls into xlsx file and save it

I am trying to convert a byte[] I got from an XLS file I have elsewhere, into a new XLSX file and the save it. 我试图将我从其他地方的XLS文件中获取的字节[]转换为新的XLSX文件并保存。 I'm using Free Spire.XML, but can't figure out how to do it. 我正在使用Free Spire.XML,但无法弄清楚如何做到这一点。

public byte[] ConvierteAXLSX(string cuerpo)
{
    Workbook wb = new Workbook();
    Worksheet sheet = wb.Worksheets[0];
    byte[] array = Convert.FromBase64String(cuerpo);
    sheet.InsertArray(array, 1, 1, true);
    wb.SaveToFile(AppDomain.CurrentDomain.BaseDirectory +  "sample.xlsx", ExcelVersion.Version2013);
    byte[] fileContent = File.ReadAllBytes(AppDomain.CurrentDomain.BaseDirectory + "sample.xlsx");
    //File.Delete(AppDomain.CurrentDomain.BaseDirectory + "sample.xlsx");
    return fileContent;
}

This code creates the XLSX file, but just inserts the byte[] into the excel file like an array, instead of converting the data. 此代码创建XLSX文件,但只是将byte []插入excel文件中,就像数组一样,而不是转换数据。

Edit: 编辑:

My problem is slightly different from that other question. 我的问题与其他问题略有不同。 I can't just read the original file and then save it again, since the file is in another server and can't access it. 我不能只读取原始文件,然后再次保存,因为该文件在另一台服务器中,无法访问它。 The best thing I can do is send the document body and parse it into byte[]. 我能做的最好的事情是发送文档正文并将其解析为byte []。

It also works if I can convert my byte[] into a XLS file and save it, then I could use the answer to the other similar question. 它也可以工作,如果我可以将我的byte []转换为XLS文件并保存它,然后我可以使用其他类似问题的答案。

Workbook workbook = new Workbook();
workbook.LoadFromFile("Input.xls");
workbook.SaveToFile("Output.xlsx", ExcelVersion.Version2013);

This is not going to war as the two file types store data completely different. 由于两种文件类型存储数据完全不同,因此不会发生争执。 The data in the xls file is stored in a proprietary binary format and the xmls file data is stored in Open XML. xls文件中的数据以专有二进制格式存储,xmls文件数据存储在Open XML中。

I did it, saved the byte[] into a XLS file, read it and saved it again into a XLSX file. 我做到了,将byte []保存到XLS文件中,读取并再次保存到XLSX文件中。

public byte[] ConvierteAXLSX(string cuerpo)
        {
            File.WriteAllBytes(AppDomain.CurrentDomain.BaseDirectory + "viejo.xls", Convert.FromBase64String(cuerpo));
            Workbook workbook = new Workbook();
            workbook.LoadFromFile(AppDomain.CurrentDomain.BaseDirectory + "viejo.xls");
            workbook.SaveToFile(AppDomain.CurrentDomain.BaseDirectory + "nuevo.xlsx", ExcelVersion.Version2013);
            byte[] fileContent = File.ReadAllBytes(AppDomain.CurrentDomain.BaseDirectory + "nuevo.xlsx");
            File.Delete(AppDomain.CurrentDomain.BaseDirectory + "viejo.xls");
            File.Delete(AppDomain.CurrentDomain.BaseDirectory + "nuevo.xlsx");
            return fileContent;
        }

Thanks for your help! 谢谢你的帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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