2010-05-27 41 views
1

我已經使用函數從數據表創建了Excel表。我想用下面的連接字符串以編程方式讀取excel表格。該字符串適用於所有其他Excel表單,但不適用於使用該函數創建的表單。我想這是因爲excel版本問題。使用File.WriteAllText()函數創建後無法讀取excel文件

OleDbConnection conn= new OleDbConnection("Data Source='" + path +"';provider=Microsoft.Jet.OLEDB.4.0;Extended Properties=Excel 8.0;";); 

任何人都可以提出一種方法,我可以創建一個Excel表,使它可以再次使用上面的查詢可讀。我無法使用Microsoft InterOp庫,因爲它不受我的主機支持。我甚至改變了不同的編碼格式。它仍然不起作用

public void ExportDataSetToExcel(DataTable dt) 
{ 
    HttpResponse response = HttpContext.Current.Response;   
    response.Clear(); 
    response.Charset = "utf-8"; 
    response.ContentEncoding = Encoding.GetEncoding("utf-8"); 
    response.ContentType = "application/vnd.ms-excel"; 
    Random Rand = new Random(); int iNum = Rand.Next(10000, 99999); 
    string extension = ".xls"; 
    string filenamepath = AppDomain.CurrentDomain.BaseDirectory + "graphs\\" + iNum + ".xls";   
    string file_path = "graphs/" + iNum + extension; 

    response.AddHeader("Content-Disposition", "attachment;filename=\"" + iNum + "\""); 
    string query = "insert into graphtable(graphtitle,graphpath,creategraph,year) VALUES('" + iNum.ToString() + "','" + file_path + "','" + true + "','" + DateTime.Now.Year.ToString() + "')"; 
    try 
    { 
     int n = connect.UpdateDb(query); 
     if (n > 0) 
     { 
      resultLabel.Text = "Merge Successfull"; 
     } 
     else 
     { 
      resultLabel.Text = " Merge Failed"; 
     } 
     resultLabel.Visible = true; 
    } 
    catch { }  
    using (StringWriter sw = new StringWriter()) 
    { 
     using (HtmlTextWriter htw = new HtmlTextWriter(sw)) 
     { 
      // instantiate a datagrid 
      DataGrid dg = new DataGrid(); 
      dg.DataSource = dt; //ds.Tables[0]; 
      dg.DataBind();     
      dg.RenderControl(htw); 
      File.WriteAllText(filenamepath, sw.ToString()); // File.WriteAllText(filenamepath, sw.ToString(), Encoding.UTF8); 
      response.Write(sw.ToString()); 
      response.End(); 
     } 
    } 
} 
+0

您是否確定創建的文檔實際上包含某些內容和某些有意義的內容?看起來你正在嘗試創建一個HTML文檔,而不是一個Excel文檔。 – 2010-05-27 10:45:08

回答

0

您似乎正在將數據集編寫爲HtmlText,然後試圖告訴它它是一個Excel文件。除非這是我錯過的東西,否則不太可能奏效,因爲Excel文件是特定的格式,因此需要使用該格式編寫。如果您創建了您創建的文件並嘗試在Excel中打開它,會發生什麼情況?

解決這個問題的一種方法是將數據寫入CSV文件,該文件可以使用Excel或OleDBConnection讀取。

+0

我也使用csv創建了該文件。但是我使用圖中的數據來生成動態圖。所以使用csv沒有意義。 – 2010-05-27 11:07:01

+0

它通常在Microsoft Excel工作表中打開。但在保存文件時,它會要求轉換爲特定的格式。 – 2010-05-27 11:07:32

-1

Folowed鏈接: C# Excel file OLEDB read HTML IMPORT

使用 擴展屬性= \「HTML進口; HDR =無; IMEX = 1 的SELECT * FROM [表名]

表名是由GetOleDbSchemaTable返回。

注意:這不會加載正常的excel ...用於該用途 擴展屬性= \「Excel 8.0; HDR =否; IMEX = 1 \ 其中表名將帶有$符號。

string full = "C:\\Temp.xls" 
      DataTable datatable = null; 
      string conString = ""; 
      OleDbConnection objConn = null; 

      try 
      { 
       //create the "database" connection string 
       connString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + full + ";Extended Properties=\"HTML Import;HDR=No;IMEX=1\""; 

       objConn = new OleDbConnection(connString); 
       // Open connection with the database. 
       objConn.Open(); 
       // Get the data table containg the schema guid. 

       dt = objConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null); 
      } 
      catch 
      { 
       throw exception 
      } 

      //no worksheets 
      if (dt == null) 
      { 
       DataCaptured = null; 
       return; 
      } 

      List<string> Sheets = new List<string>(); 

      // Add the sheet name to the string array. 

      foreach (DataRow row in dt.Rows) 
      { 
       string name = row["TABLE_NAME"].ToString(); 

       if (string.IsNullOrEmpty(name) == false) 
       { 
        Sheets.Add(name); 
       } 
      } 

      //no worksheets 
      if (excelSheets.Count == 0) 
      { 
       return; 
      } 

      Dataset dataSet = new DataSet(); 

      int sheetCount = excelSheets.Count; 

      for (int i = 0; i < sheetCount; i++) 
      { 
       string sheetName = excelSheets[i]; 

       OleDbDataAdapter ad = new OleDbDataAdapter("SELECT * FROM [" + sheetName + "]", connString); 

       DataTable data = new DataTable(); 
       try 
       { 
        ad.Fill(data); 
       } 
       catch 
       { 
        throw exception 
       } 

       data.TableName = sheetName; 
       dataSet.Tables.Add(data); 

       adapter.Dispose(); 
      } 

      objConn.Close(); 

     return dataSet; 
+0

-1代碼錯誤。 – tomfanning 2012-09-27 17:18:52

相關問題