• DataTable数据导出CSV文件


    public static void SaveAsExcel(DataTable dt1)
    {
    //System.Windows.Forms.SaveFileDialog sfd = new System.Windows.Forms.SaveFileDialog();// = new SaveFileDialog();
    //sfd.Filter = "导出文件 (*.csv)|*.csv";
    //sfd.FilterIndex = 0;
    //sfd.RestoreDirectory = true;
    //sfd.Title = "导出文件保存路径";
    //sfd.ShowDialog();
    string SystemTime;
    SystemTime = DateTime.Now.Year.ToString()+DateTime.Now.Month+DateTime.Now.Day+DateTime.Now.Hour+DateTime.Now.Minute+DateTime.Now.Second;
    string strFilePath = GlobalVar.Path+"DataQuery\" + SystemTime + ".csv";// sfd.FileName;
    StringBuilder strValue = new StringBuilder();
    StreamWriter sw = new StreamWriter(new FileStream(strFilePath, FileMode.CreateNew), Encoding.Default); // 输出表头
    userControlDataQuery bd = new userControlDataQuery(); //这里的BusiDetail是你执行导出操作所在的BusiDetail.xaml
    bd.WriteHeader(sw);
    int i, j,k;
    ushort count=0;
    foreach (DataRow dr in dt1.Rows)
    {
    strValue.Remove(0, strValue.Length);
    for ( i = 0; i <= dt1.Columns.Count - 1; i++)
    {
    if(i==2)
    count = Convert.ToUInt16(dr[i]);
    if (i == 4)
    {
    byte[] bValue = (byte[])dr[i];

    ushort[] uValue = new ushort[count];
    ushort max, min;
    max = 0;
    min = 0;
    for (j = 0; j < count; j++)
    {
    uValue[j] = (ushort)(bValue[2 * j + 1] * 256 + bValue[2 * j]);
    if (max < uValue[j])
    max = uValue[j];
    if (min > uValue[j])
    min = uValue[j];
    }
    strValue.Append("最大值="+max+";"+"最小值="+min);
    strValue.Append(",");
    strValue.Append(Select.Scale);
    strValue.Append(",");
    continue;
    }

    strValue.Append(dr[i].ToString());
    strValue.Append(",");
    if (i == (dt1.Columns.Count - 1))
    {

    for(k=0;k<4;k++)
    {
    if (k == 0)
    {
    strValue.Append(Select.Alarmup);
    strValue.Append(",");
    }
    if (k == 1)
    {
    strValue.Append(Select.Alarmdown);
    strValue.Append(",");
    }
    if (k == 2)
    {
    strValue.Append(Select.Dangerup);
    strValue.Append(",");
    }
    if (k == 3)
    {
    strValue.Append(Select.Dangerdown);
    strValue.Append(",");
    }

    }

    }

    }
    strValue.Remove(strValue.Length - 1, 1);//移出掉最后一个,字符
    sw.WriteLine(strValue);
    }
    sw.Close();
    System.Windows.MessageBox.Show("导出文件成功!","成功", MessageBoxButton.OK,MessageBoxImage.Information);
    } // 输出表头

    private void WriteHeader(StreamWriter sw)
    {
    string strHeader = "监测对象,监测时间,采样长度,采样频率,数值,单位,状态,报警上限,报警下限,危险上限,危险下限";
    sw.WriteLine(strHeader);
    }

  • 相关阅读:
    Linux命令记录-Tomcat(七)
    Linux命令记录-PostgreSql(六)
    Linux命令记录-Mysql(五)
    Linux Crontab实现定时任务
    Linux命令记录-Java环境(四)
    Linux命令记录-防火墙(三)
    Linux命令记录-服务相关(二)
    Linux命令记录-环境准备(一)
    Linux 系统安装,磁盘分区要点
    java之Collection类
  • 原文地址:https://www.cnblogs.com/sason/p/5547423.html
Copyright © 2020-2023  润新知