簡體   English   中英

將Excel文件讀入內存,然后將其寫回到磁盤

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

我最終試圖讀取文件,將其存儲在Cassandra數據庫的blob中,然后再將其寫回到磁盤。 遇到問題,並簡化為以下代碼來演示該問題。 相同的代碼適用於.txt和.csv文件,但不適用於Excel電子表格。 我不確定這是否是編碼問題以及如何解決。 我嘗試了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);
}

原始文件大小為536,576。 Test1是1,282,808,而Test2是536,578。 顯然,我要讀取與讀入相同大小的文件,然后將對其進行文件比較以驗證它。 我也希望該程序可以使用任何文件類型,只是Excel是第一個演示該問題的文件。

讀寫二進制文件應該使用File.ReadAllBytesFile.WriteAllBytes代替。 希望能幫助到你!

此StackOverflow幫助說明ReadAllBytes和ReadAllText之間的區別: 為什么File.ReadAllBytes結果與使用File.ReadAllText時有所不同?

我會從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>();
    }
}

然后,您可以構建字符串並存儲到您喜歡的任何位置。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM