asp.net 将数据从内存流转换为数据表

vi4fp9gy  于 2022-11-26  发布在  .NET
关注(0)|答案(2)|浏览(139)

我尝试从SharePoint站点上的Excel文件URL中获取数据,并将其放入数据表中,但出现以下错误:
输入流不是有效的二进制格式。起始内容(以字节为单位)为:50-4B
下面是我使用的代码:-

WebClient webClient = new WebClient();
webClient.Credentials = CredentialCache.DefaultNetworkCredentials;
byte[] data = webClient.DownloadData("http://sp2010sw127:2000/eur/Home/TestLibrary/Details.xlsx");
MemoryStream memoryStreamOfFile = new MemoryStream(data);
BinaryFormatter formatter = new BinaryFormatter();
memoryStreamOfFile.Seek(0, SeekOrigin.Begin);
DataTable dt = (DataTable)formatter.Deserialize(memoryStreamOfFile);

请多多指教。

nxowjjhe

nxowjjhe1#

不应使用binaryformatter。它很危险。
https://aka.ms/binaryformatter

v7pvogib

v7pvogib2#

正在下载的数据是Excel电子表格;这与DataTable完全不同;当您尝试执行以下操作时:

DataTable dt = (DataTable)formatter.Deserialize(memoryStreamOfFile);

然后,您尝试将表示Excel电子表格的字节流反序列化为DataTable对象,这是不可能的。
相反,您可以先下载文件:

WebClient webClient = new WebClient();
webClient.Credentials = CredentialCache.DefaultNetworkCredentials;
webClient.DownloadFile(
              "http://sp2010sw127:2000/eur/Home/TestLibrary/Details.xlsx",
              "C:\\Details.xlsx");

然后使用下面的方法(我从我的答案here中定制了这个方法):

DataTable myData = LoadFromExcelFile("C:\\Details.xlsx");

请注意,您需要考虑一个更合适的位置来保存文件,并且还需要查看SELECT查询以从工作表中获取所需的列(在下面的示例中名为[Sheet1$])。

public DataTable LoadFromExcelFile(string filePath)
{
    String excelConnString = String.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=\"Excel 12.0\"", filePath);
    //Create Connection to Excel work book 
    using (OleDbConnection excelConnection = new OleDbConnection(excelConnString))
    {
        //Create OleDbCommand to fetch data from Excel - you can query the sheet as if it were a sql table effectively
        using (OleDbCommand cmd = new OleDbCommand("SELECT [Column1],[Column2],[Column3] from [Sheet1$]", excelConnection))
        {
            excelConnection.Open();
            using (OleDbDataReader dReader = cmd.ExecuteReader())
            {
                DataTable myData = new DataTable();
                myData.Load(dReader);
                return myData;
            }
        }
    }
}

相关问题