我正在使用oracle数据库和asp.net 2013 ..
以下代码是我将数据从数据库导出到Excel文件的方式。
private DataTable GetData(string sqlcommand)
{
try
{
string sapno = "SAP NO";
string partno = "PART NO";
string partdesc = "PART DESCRIPTION";
string minQty = "MINIMUM QUANTITY";
string QOH = "QUANTITY ON HAND";
string category = "CATEGORY";
string equipment = "EQUIPMENT";
readdata.selectdata(ds, sqlcommand);
DataTable dt = ds.Tables[0];
dt.Columns[0].ColumnName = sapno;
dt.Columns[1].ColumnName = partno;
dt.Columns[2].ColumnName = partdesc;
dt.Columns[3].ColumnName = minQty;
dt.Columns[4].ColumnName = QOH;
dt.Columns[5].ColumnName = category;
dt.Columns[6].ColumnName = equipment;
ds.Tables.Clear();
return dt;
}
catch (Exception ex)
{
throw ex;
}
}
protected void btnDownload_Click(object sender, EventArgs e)
{
//Get the data from database into datatable
string sqlcommand=null;
if (validate.isEmpty(txtPartNo.Text) == true || Session["SAPNOIR"] ==null)
{
sqlcommand = "SELECT SAPNO , PARTNO, PARTDESC, MINQTY, QOH , CATEGORY, EQUIPMENT FROM INVENTORY";
}
else
{
sqlcommand = "SELECT SAPNO, PARTNO, PARTDESC, MINQTY, QOH , CATEGORY, EQUIPMENT FROM INVENTORY WHERE SAPNO = '" + Session["SAPNOIR"] + "'";
Session["SAPNOIR"] = null;
}
DataTable dt = GetData(sqlcommand);
//Create a dummy GridView
GridView GridView1 = new GridView();
GridView1.AllowPaging = false;
GridView1.DataSource = dt;
GridView1.DataBind();
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition",
"attachment;filename=DataTable.xls");
Response.Charset = "";
Response.ContentType = "application/vnd.ms-excel";
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
for (int i = 0; i < GridView1.Rows.Count; i++)
{
//Apply text style to each Row
GridView1.Rows[i].Attributes.Add("class", "textmode");
}
GridView1.RenderControl(hw);
//style to format numbers to string
string style = @"<style> .textmode { mso-number-format:\@; } </style>";
Response.Write(style);
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();
}
当我打开excel文件时,所有中文字符都将成为不可读的字符。任何人都知道如何在导出到excel文件时显示中文字符!!
我尝试在我的web.config中添加编码窗口1250,但它仍然无法正常工作。 有人请帮忙。感谢
感谢您的评论是建议!它非常适合!
答案 0 :(得分:1)
我找出了原因。传入excel的所有数据必须首先进行编码,否则计算机将立即传入..
添加下面的代码然后问题解决!!!
Response.ContentEncoding = System.Text.Encoding.Unicode;
Response.BinaryWrite(System.Text.Encoding.Unicode.GetPreamble());