httpWebRequest下载并parsingexcel文件?
我正在寻找一种方法来使用httpWebRequest从URL下载Excel文件,并以某种方式parsing它 – 这是否意味着将其转换为.csv文件,所以我可以简单地使用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; } }
我的理解是contents
应该是一个字节数组? 我怎样才能正确地下载这个excel文件并parsing响应?
如何使用WebClient类下载Excel文件,使用DownloadFile()
而不是DownloadData()
(Simpler)。
string destFilename = HttpContext.Current.Server.MapPath("~/YourExcelFile.xlsx"); WebClient client = new WebClient(); client.DownloadFile("http://www.blabla.com/YourExcelFile.xlsx", destFilename);
这应该将文件下载到您的应用程序的根目录。
下一步是读取文件。 根据我的经验,以编程方式读取Excel文件的最简单方法就是使用SQL / OleDB查询它。
示例如何将文件的第一个工作表读取到DataTable中:
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);
帮助函数获取连接string:
// 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文件。
- 阿拉伯语词汇出口到Excel的asp.net
- 当调用AddIns.Item 时,索引无效(从HRESULTexception:0x8002000B(DISP_E_BADINDEX)))
- c#excel插件工作簿closures事件
- 从C#中的Excel文件获取行
- 将DataTable列表与string列表进行比较
- 如何使用Exceljoin项目的签名证书创buildVisual Studio安装项目
- 如何将Excel和c#之间的“double”转换为“datetime”
- 阅读excel文件,而不需要在服务器中的整个文件
- RibbonControl属性callback(getPressed,getSupertip等)永不更新