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);
}

上一篇:12.引入依赖项目的时候,如果找不到jar


下一篇:[javaSE] 集合框架(TreeSet)