使用StringWriter 导出Excel

DataTable dt = ExportExcel(Sql);//执行查询

StringWriter sw = new StringWriter();

//datatable写入TextWriter

DataTableToWriter(dt, sw);

string filePath = "TempFile//" + DateTime.Now.ToString("yyyyMMddhhmmss") + ".xls";

//创建Excel文件

File.Create(Server.MapPath("//" + filePath));StreamWriter fileWriter = new StreamWriter(Server.MapPath("//" + filePath),true,System.Text.Encoding.GetEncoding("GB2312"));

fileWriter.WriteLine(sw);

fileWriter.Close();

fileWriter.Dispose(); 

 

 

///datatable写入TextWriter

public void DataTableToWriter(DataTable dt, StringWriter w)

{

    try

    {

        //读取表头

        for (int i = 0; i < dt.Columns.Count; i++)

        {

             w.Write(dt.Columns[i]);

             w.Write('\t');

         }

         w.Write("\r\n");

         object[] values = new object[dt.Columns.Count];

         //读取数据行

         foreach (DataRow dr in dt.Rows)

         {

              values = dr.ItemArray;

              for (int i = 0; i < dt.Columns.Count; i++)

              {

                   w.Write(values[i]);

                   w.Write('\t');

               }

               w.Write("\r\n");

          }

          w.Flush();

          w.Close();

    }

    catch

    {

        w.Close();

    }

}

你可能感兴趣的:(开发语言)