C# 使用file.WriteAllText()函数创建excel文件后,无法读取该文件

C# 使用file.WriteAllText()函数创建excel文件后,无法读取该文件,c#,asp.net,excel,C#,Asp.net,Excel,我已经使用函数从datatable创建了一个excel工作表。我想使用下面的连接字符串以编程方式阅读excel工作表。该字符串适用于所有其他excel工作表,但不适用于我使用该函数创建的工作表。我想这是因为excel版本的问题 OleDbConnection conn= new OleDbConnection("Data Source='" + path +"';provider=Microsoft.Jet.OLEDB.4.0;Extended Properties=Excel 8.0;"

我已经使用函数从datatable创建了一个excel工作表。我想使用下面的连接字符串以编程方式阅读excel工作表。该字符串适用于所有其他excel工作表,但不适用于我使用该函数创建的工作表。我想这是因为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();
        }
    }
}

您似乎正在将数据集编写为HtmlText,然后试图告诉它它是一个Excel文件。因为Excel文件是一种特定的格式,所以需要以这种格式编写,除非我遗漏了不太可能工作的内容。如果您获取已创建的文件并尝试在Excel中打开它,会发生什么情况

一种解决方法是将数据写入CSV文件,该文件可通过Excel或OLEDB连接读取。

链接如下:

使用 扩展属性=\HTML导入;HDR=否;IMEX=1 从[tablename]中选择*

tablename是从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;

您是否确保创建的文档实际上包含了一些内容以及一些有意义的内容?看起来您正在尝试创建HTML文档,而不是Excel文档。我也使用csv创建了该文件。但我使用graph中的数据生成一个动态图。因此,使用csv毫无意义。它通常在Microsoft Excel工作表中打开。但在保存文件时,它要求转换为特定格式。