将Excel字节数组数据转换为Datatable C#API

要求客户端将以字节数组的形式发送Excel数据(将提供相同的API链接给客户端)

现在,当API收到字节数组时,我想转换为数据表以转换为XML。

下面是我尝试过的代码

 public string ConvertExcelByteArraytoXML()
        {

            byte[] Excelbytes = null;
            FileStream fs = File.OpenRead("C:\\PRATAP FOLDER\\test.xlsx");            
            BinaryReader binaryReader = new BinaryReader(fs);
            Excelbytes = binaryReader.ReadBytes((int)fs.Length);
            string CreateXMLFILE = string.Empty;

       // the above code was to get byte array from excel 

            DataSet tempDataSet = new DataSet();
            DataTable dt;
            // Deserializing into datatable    
            using (MemoryStream stream = new MemoryStream(Excelbytes))
            {
                BinaryFormatter bformatter = new BinaryFormatter();
                dt = (DataTable)bformatter.Deserialize(stream);

            }
            // Adding DataTable into DataSet    
            tempDataSet.Tables.Add(dt);

           using (StringWriter sw = new StringWriter())
            {
                dt.WriteXml(sw);
                CreateXMLFILE = sw.ToString();
            }
          return CreateXMLFILE;

}

处抛出错误

dt = (DataTable)bformatter.Deserialize(stream);

  

{“输入流不是有效的二进制格式。起始内容   (以字节为单位)是:50-4B-03-04-14-00-06-00-08-00-00-00-21-00-EB-7A-D2   ...“}

有人可以建议我在这里做错什么吗

coldboyjack 回答:将Excel字节数组数据转换为Datatable C#API

就像我在评论中提到的那样,您可以尝试以下代码来转换字节数组

到数据表。

代码:

class Program
    {
        static void Main(string[] args)
        {
            byte[] b = File.ReadAllBytes("D:\\2.xlsx");      // you get from the client
            File.WriteAllBytes("test.xlsx",b);             //Create an hourly file
            DataTable table = Exceltodatatable("test.xlsx");  // convert it to datatable
            File.Delete("test.xlsx");                         // delete the file
        }

        public static DataTable Exceltodatatable(string path)
        {
            DataTable dt = new DataTable();
            string connectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";" + "Extended Properties='Excel 12.0 Xml;HDR=YES;IMEX=1;MAXSCANROWS=0'";
            using (OleDbConnection conn = new OleDbConnection(connectionString))
            {
                using (OleDbCommand comm = new OleDbCommand())
                {
                    string sheetName = "sheet1";
                    comm.CommandText = "Select * from [" + sheetName + "$]";
                    comm.Connection = conn;
                    using (OleDbDataAdapter da = new OleDbDataAdapter())
                    {
                        da.SelectCommand = comm;
                        da.Fill(dt);
                        return dt;
                    }
                }

            }
        }
    }
本文链接:https://www.f2er.com/3021334.html

大家都在问