zoukankan      html  css  js  c++  java
  • c#导出Excel

    使用IO流,使用文件流在磁盘创建一个 Excel 文件,然后使用流写入数据

    public static void ExportExcel(DataTable dt)
    {
    string path = AppDomain.CurrentDomain.BaseDirectory + "Export/";
    if (!Directory.Exists(path))//验证路径是否存在
    {
    //不存在则创建
    Directory.CreateDirectory(path);
    }
    //设置导出文件路径
    //string path = HttpContext.Current.Server.MapPath("Export/");
    //设置新建文件路径及名称
    //string savePath = path + DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss") + ".xls";
    string savePath = path + DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss") + ".xls";
    if (File.Exists(savePath))
    {
    File.Delete(savePath);
    }
    //创建文件
    FileStream file = new FileStream(savePath, FileMode.CreateNew, FileAccess.Write);
    //以指定的字符编码向指定的流写入字符
    StreamWriter sw = new StreamWriter(file, Encoding.GetEncoding("GB2312"));
    StringBuilder strbu = new StringBuilder();
    //写入标题
    for (int i = 0; i < dt.Columns.Count; i++)
    {
    strbu.Append(dt.Columns[i].ColumnName.ToString() + " ");
    }
    //加入换行字符串
    strbu.Append(Environment.NewLine);
    //写入内容
    for (int i = 0; i < dt.Rows.Count; i++)
    {
    for (int j = 0; j < dt.Columns.Count; j++)
    {
    strbu.Append(dt.Rows[i][j].ToString() + " ");
    }
    strbu.Append(Environment.NewLine);
    }
    sw.Write(strbu.ToString());
    sw.Flush();
    file.Flush();
    sw.Close();
    sw.Dispose();
    file.Close();
    file.Dispose();
    }

  • 相关阅读:
    用归并排序或树状数组求逆序对数量 poj2299
    UVA10600 次小生成树
    最小生成树求最大比率 UVALive
    求树的重心 poj 1655
    求树的直径+并查集(bfs,dfs都可以)hdu4514
    树形DP+RMQ+尺取法 hdu4123
    区间dp 51nod1021
    LCS poj1080
    最长公共子序列hdu1503
    python No handlers could be found for logger错误的解决
  • 原文地址:https://www.cnblogs.com/ling-cun/p/10072021.html
Copyright © 2011-2022 走看看