我已经使用函数从数据表创建了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();
}
}
}
您是否确定创建的文档实际上包含某些内容和某些有意义的内容?看起来你正在尝试创建一个HTML文档,而不是一个Excel文档。 – 2010-05-27 10:45:08