C# httpWebRequest下载并解析excel文件?
我正在寻找一种方法,使用httpWebRequest从url下载一个excel文件,并以某种方式对其进行解析——这是否意味着将其转换为.csv文件,以便我可以简单地使用C# httpWebRequest下载并解析excel文件?,c#,excel,C#,Excel,我正在寻找一种方法,使用httpWebRequest从url下载一个excel文件,并以某种方式对其进行解析——这是否意味着将其转换为.csv文件,以便我可以简单地使用TextFieldParser,或者将其作为excel文件保留,我不知道 private byte[] GetExcelFile() { var httpWebRequest = (HttpWebRequest)WebRequest.Create("url_To_Excel_File");
TextFieldParser
,或者将其作为excel文件保留,我不知道
private byte[] GetExcelFile()
{
var httpWebRequest = (HttpWebRequest)WebRequest.Create("url_To_Excel_File");
httpWebRequest.ContentType = "application/vnd.ms-excel";
httpWebRequest.Method = "GET";
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
try
{
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var contents = streamReader.ReadToEnd();
return contents;
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
throw;
}
}
我的理解是,
内容
应该是一个字节数组?如何正确下载此excel文件并解析响应?如何使用WebClient类下载excel文件,使用DownloadFile()
而不是DownloadData()
(更简单)
这将把文件下载到应用程序的根目录下
下一步是读取文件。根据我的经验,以编程方式读取Excel文件最简单的方法就是使用SQL/OleDB查询它
如何将文件的第一页读入数据表的示例:
string connectionString = GetExcelConnectionString(destFilename);
string sheetName = GetFirstSheet(filePath);
OleDbConnection excelCon = new OleDbConnection(connectionString);
OleDbDataAdapter adapter = new OleDbDataAdapter(String.Format("select * from [{0}]", sheetName), excelCon);
DataTable dataTable = new DataTable("ExcelDocument");
adapter.Fill(dataTable);
获取连接字符串的助手函数:
// Currently only supports Excel 12.0 (.xlsx files), the connection string for .xls is a little different.
public string GetExcelConnectionString(string filePath)
{
return "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filePath + ";Extended Properties=Excel 12.0;";
}
要读取文件中第一张图纸的名称,请执行以下操作:
public string GetFirstSheet(string filePath)
{
string connectionString = GetExcelConnectionString(filePath);
using (OleDbConnection connection = new OleDbConnection(connectionString))
{
connection.Open();
DataTable dtSheet = connection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
return dtSheet.Rows[0]["TABLE_NAME"].ToString();
}
return String.Empty;
}
现在,您应该将文件的内容放在一个DataTable中,这样就可以轻松地处理数据
请注意,这只是给你一个想法,可能并不完美。您可能希望在处理后进行清理—例如,从应用程序的根目录中删除excel文件。为什么不改用WebClient类?使用DownloadData()下载文件-它返回一个字节数组。如果您需要读取该文件,我建议您使用OleDB查询它。请参见此处:您能否提供在WebClient类中使用
DownloadData()
的示例代码?您不能使用oledb从memorystream中读取excel,您必须先将其保存到文件中。excel生成的xsl文件中的excel文件通常为二进制格式,不使用excel/oledb将无法解析。然而,如果你得到一个CSV文件,你可以在内存中解析它。但excel将其保存到磁盘,并使用OleDB读取。
public string GetFirstSheet(string filePath)
{
string connectionString = GetExcelConnectionString(filePath);
using (OleDbConnection connection = new OleDbConnection(connectionString))
{
connection.Open();
DataTable dtSheet = connection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
return dtSheet.Rows[0]["TABLE_NAME"].ToString();
}
return String.Empty;
}