2011-04-14 98 views
0

我正在使用:`private void get_stocks_data() { byte [] result; byte [] buffer = new byte [4096];下載並保存excel文件

 WebRequest wr = WebRequest.Create("http://www.tase.co.il/TASE/Pages/ExcelExport.aspx?sn=he-IL_ds&enumTblType=AllSecurities&Columns=he-IL_Columns&Titles=he-IL_Titles&TblId=0&ExportType=1"); 

     using (WebResponse response = wr.GetResponse()) 
     { 
      using (Stream responseStream = response.GetResponseStream()) 
      { 
       using (MemoryStream memoryStream = new MemoryStream()) 
       { 
        int count = 0; 
        do 
        { 
         count = responseStream.Read(buffer, 0, buffer.Length); 
         memoryStream.Write(buffer, 0, count); 
        } while (count != 0); 
        result = memoryStream.ToArray(); 
        write_data_to_excel(result); 

       } 
      } 
     }` 

下載Excel文件,

而且這種方法來填補我的電腦上的文件:

private void write_data_to_excel(byte[] input) 
    { 
     StreamWriter str = new StreamWriter("stockdata.xls"); 

     for (int i = 0; input.Length > i; i++) 
     { 
      str.WriteLine(input[i].ToString()); 
     } 
     str.Close(); 
    } 

的結果是,我得到了很多的數字... 什麼我做錯了嗎?我下載的文件是Excel 2003版本,在我的電腦上我有2007 ... 謝謝。

回答

1

問題是在你的Write_data_to_excel功能抽象
與您使用StreamWriter.WriteLine方法需要字符串,
你正在傳遞字節作爲字符串,所以你的二進制值說10將現在字符串10
嘗試FileStream f = File.OpenWrite("stockdata.xlsx");
f.Write(input,0,input.Length);
這將工作。

+0

好多了,那可行......但現在我發現我下載了錯誤的URL .. 。我正在下載的頁面上有一個按鈕,應該點擊他的按鈕,然後選擇excel 2003格式下載...那麼我應該給什麼網址?該網頁是在tase.co.il/TASE/Products/Stocks/ MarketData和excel文件是在點擊具有excel圖標的按鈕時給出的,然後選擇excel 2003(和下載開始)...我應該給什麼網址?謝謝。 – 2011-04-15 06:49:03

+0

實際上Excel按鈕執行一個頁面'javascript:customWindowOpen('/ TASE/Pages/ExcelExport.aspx?sn = none&enumTblType = allShares&Columns = noneColumns&Titles = noneTitles&action = 1&SubAction = 0&GridId = 33&CurGuid = {727FE319-7530-460E-9444-E9FB85BCF378} &ExportType = 1','_blank','scrollbars = yes; toolbar = yes; menubar = yes; resizable = yes',800,450); return false;' 所以你應該調用'/TASE/Pages/ExcelExport.aspx '與上述所有參數一樣,但是每次當您要調用頁面時都必須查找參數(GridID和CurGuid)。 – EmersioN 2011-04-20 08:21:54

5

我建議您使用WebClient.DownloadFile()來代替。

這是一種更高層次的方法將從手動創建的要求,處理編碼等

+0

好吧,使用WebClientgives給出一些計劃...但我沒有下載正確的url ...我下載的頁面上有一個按鈕,他應該點擊buttom,然後選擇excel 2003格式下載...所以我應該給什麼網址?該網頁在http://www.tase.co.il/TASE/Products/Stocks/MarketData/,並且在點擊具有excel圖標的按鈕時給出excel文件,然後選擇Excel 2003(和下載開始)...我應該給什麼網址? – 2011-04-14 01:19:50

+0

在我的情況下,網址是http://www.tase.co.il/TASE/Pages/ExcelExport.aspx?sn=none&enumTblType=allshares&Columns=noneColumns&Titles=noneTitles&action=1&SubAction=0&GridId=33&CurGuid={0BDA5110-EF93-44CB- A0F0-468C6F502B51}&ExportType = 1,但它似乎包含某種類型的會話令牌,所以它可能比僅檢索URL – 2011-04-14 01:33:35