简体   繁体   English

将Excel文件读入内存,然后将其写回到磁盘

[英]Read an Excel file into memory, and then write it back to disk

I'm ultimately trying to read a file, store in a blob in a Cassandra database, then later write it back to disk. 我最终试图读取文件,将其存储在Cassandra数据库的blob中,然后再将其写回到磁盘。 Was having issues, and simplified to the following code that demonstrates the issue. 遇到问题,并简化为以下代码来演示该问题。 The same code works fine with .txt and .csv files, but doesn't work with an Excel spreadsheet. 相同的代码适用于.txt和.csv文件,但不适用于Excel电子表格。 I'm not sure if it's an encoding issue, and how to fix it. 我不确定这是否是编码问题以及如何解决。 I tried Encoding.Unicode, but that didn't work either. 我尝试了Encoding.Unicode,但这也不起作用。

static void testFileReadWrite()
{
    string filenameIn = @"c:\demo\Timesheet.xls";
    string filenameOut1 = @"c:\demo\Timesheet_Test1.xls";
    string filenameOut2 = @"c:\demo\Timesheet_Test2.xls";

    string fileContents1 = File.ReadAllText(filenameIn);
    File.WriteAllText(filenameOut1, fileContents1);

    string fileContents2 = File.ReadAllText(filenameIn, Encoding.Unicode);
    File.WriteAllText(filenameOut2, fileContents2, Encoding.Unicode);
}

Original file size was 536,576. 原始文件大小为536,576。 Test1 was 1,282,808 and Test2 was 536,578. Test1是1,282,808,而Test2是536,578。 Obviously, I want the same size file out as I read in, then I will do a file compare on it to validate it. 显然,我要读取与读入相同大小的文件,然后将对其进行文件比较以验证它。 I also want the program to work with any file type, it's just that Excel was the first one that demonstrated the issue. 我也希望该程序可以使用任何文件类型,只是Excel是第一个演示该问题的文件。

Reading and writing binary files should be done using File.ReadAllBytes and File.WriteAllBytes instead. 读写二进制文件应该使用File.ReadAllBytesFile.WriteAllBytes代替。 Hope it helps! 希望能帮助到你!

This StackOverflow helps explain the difference between ReadAllBytes and ReadAllText: Why is File.ReadAllBytes result different than when using File.ReadAllText? 此StackOverflow帮助说明ReadAllBytes和ReadAllText之间的区别: 为什么File.ReadAllBytes结果与使用File.ReadAllText时有所不同?

I would the 'OfficeOpenXml' library from Microsoft and read the excel file as you like. 我会从Microsoft获得“ OfficeOpenXml”库,然后根据需要读取excel文件。

//
using OfficeOpenXml;

//
read the file using file stream
using (var stream= new StreamReader("filePath"))
{
     // then use the stream to extract the excel specific data
     using (var excelPackage = new ExcelPackage(stream))
    {
        var sheet = excelPackage.Workbook.Worksheets[1];
        var cell1= sheet.Cells[1, 1].GetValue<string>();
    }
}

Then you can build up your string and store to anywhere you like. 然后,您可以构建字符串并存储到您喜欢的任何位置。

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

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