使用File.WriteAllText()函数创建excel文件后无法读取它

时间:2010-05-27 10:39:02

标签: 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;";);  

任何人都可以建议一种方法,我可以创建一个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();
        }
    }
}

2 个答案:

答案 0 :(得分:0)

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

一种方法是将您的数据写为CSV文件,可以使用Excel或OleDBConnection读取。

答案 1 :(得分:-1)

链接: C# Excel file OLEDB read HTML IMPORT

使用 扩展属性= \“HTML导入; HDR =否; IMEX = 1 select * from [tablename]

tablename从GetOleDbSchemaTable返回。

注意:这不会加载正常的excel ...用于该用途 扩展属性= \“Excel 8.0; HDR =否; IMEX = 1 \ 表名将带有$ sign。

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;