日期:2014-05-17  浏览次数:20442 次

关于.net导出execl问题
[color=#FF0000]StringWriter sw = new StringWriter();

  BLL.FinanceManage Myfin = new YouMayFinance.BLL.FinanceManage();

   
  sw.WriteLine("客户名称\t客户类别\t产品重量\t产品价格\t总金额\t汽车车牌\t交易时间\t是否含税");

  decimal a, b;

  DataTable dt = Myfin.FinanceListDetailsByTime(Convert.ToInt16(DropDownList1.SelectedValue), TextBox1.Text, Convert.ToDateTime(StartTime.Text.ToString()), Convert.ToDateTime(EndTime.Text.ToString()), out a, out b);

  foreach (DataRow dr in dt.Rows)
  {
  sw.WriteLine(dr["CustomerName"] + "\t" + dr["TypeName"] + "\t" + dr["CoalWeight"] + "\t" + dr["CoalPrice"] + "\t" + dr["Total"] + "\t" + dr["CarID"] + "\t" + dr["FinanceTime"] + "\t" + dr["IsTaxn"]);
  }


  Response.AddHeader("Content-Disposition", "attachment; filename=test.xls");

  Response.ContentType = "application/vnd.ms-excel";//type=excel  

  Response.ContentEncoding = System.Text.Encoding.GetEncoding("UTF-8");

  Response.Write(sw.ToString());

  Response.End(); [/color]

问题是导出后在execl中查看是乱码

------解决方案--------------------
说到导出EXCEL我建议楼主还是用NPOI~!

可以去网上查一下,这个是我到目前为止认为最好的导出EXCEL的方案~!

你这样用普通的IO方法来导出不觉得累?而且,有很多效果无法实现```````
------解决方案--------------------
public void CreateExcel(DataSet ds)
{
HttpResponse resp;
resp = Page.Response;
resp.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
resp.AppendHeader("Content-Disposition", "attachment;filename=Excel.xls");
string colHeaders = "", ls_item = "";
int i = 0;

//定义表对象与行对像,同时用DataSet对其值进行初始化 
DataTable dt = ds.Tables[0];
DataRow[] myRow = dt.Select("");
// typeid=="1"时导出为EXCEL格式文件;typeid=="2"时导出为XML格式文件 

//取得数据表各列标题,各标题之间以\t分割,最后一个列标题后加回车符 
for (i = 0; i < dt.Columns.Count - 1; i++)
colHeaders += dt.Columns[i].Caption.ToString() + "\t";
colHeaders += dt.Columns[dt.Columns.Count - 1].Caption.ToString() + "\n";
//向HTTP输出流中写入取得的数据信息 
resp.Write(colHeaders);

//逐行处理数据 
foreach (DataRow row in myRow)
{
//在当前行中,逐列获得数据,数据之间以\t分割,结束时加回车符\n 
for (i = 0; i < dt.Columns.Count - 1; i++)
ls_item += row[i].ToString() + "\t";
ls_item += row[dt.Columns.Count - 1].ToString() + "\n";
resp.Write(ls_item);
//当前行数据写入HTTP输出流,并且置空ls_item以便下行数据 

ls_item = "";


//写缓冲区中的数据到HTTP头文件中 
resp.End();
}
}

------解决方案--------------------
C# code
protected void AddExcel(DataSet ds)
{
DataTable dt = ds.Tables[0];

string fileName = Guid.NewGuid() + ".xls";

Excel.Application excel = new Excel.ApplicationClass();

int rowIndex = 1;
int colIndex = 0;

excel.Application.Workbooks.Add(true);

foreach (DataColumn col in dt.Columns)
{
colIndex++;
excel.Cells[1, colIndex] = col.ColumnName;
}

foreach (DataRow row in dt.Rows)
{
rowIndex++;
colIndex = 0;
for (colIndex = 0; colIndex < dt.Columns.Count; colIndex++)
{
excel.Cells[rowIndex, colIndex + 1] = row[colIndex].ToString();
}
}

excel.Visible = false;
excel.ActiveWorkbook.SaveAs(fileName, Excel.XlFileFormat.xlExcel9795, null, null, false, f