導出數據類,主要包括導出XML文件和文本文件
using System;
using System.IO;
using System.Windows.Forms;
using System.Data;
using System.Text;
namespace train
...{
/**//// <summary>
/// ExportData:導出數據
/// </summary>
public class ExportData
...{
private DataTable table;
private DataSet ds;
public ExportData()
...{
table=new DataTable();
ds=new DataSet();
}
/**//// <summary>
/// 導出文本文件
/// </summary>
/// <param name="printtable">包含要導出數據的DataTable</param>
/// <returns>返回一個bool值指示導出是否成功</returns>
public bool Export(DataTable printtable)
...{
table=printtable;
SaveFileDialog dialog=new SaveFileDialog();
dialog.Filter="文本文件|*.txt";
dialog.ShowDialog();
string path=dialog.FileName;
if(path.Length==0)
...{
return false;
}
StreamWriter writer=new StreamWriter(@path,false,Encoding.UTF8,128);
try
...{
for(int i=0;i<table.Columns.Count;i++)
...{
writer.Write(table.Columns[i].ColumnName+" ");
}
writer.WriteLine("");
for(int i=0;i<table.Rows.Count;i++)
...{
for(int j=0;j<table.Columns.Count;j++)
...{
writer.Write(table.Rows[i][j].ToString()+" ");
}
writer.WriteLine("");
}
return true;
}
catch(Exception e)
...{
Console.WriteLine(e);
return false;
}
finally
...{
writer.Flush();
writer.Close();
}
}
/**//// <summary>
/// 導出XML文件
/// </summary>
/// <param name="printtable">包含要到處數據的DataTable</param>
/// <returns>返回一個bool值指示導出是否成功</returns>
public bool exportXML(DataTable printtable)
...{
ds.Tables.Add(printtable);
SaveFileDialog dialog=new SaveFileDialog();
dialog.Filter="XML文件|*.XML";
dialog.ShowDialog();
string path=dialog.FileName;
if(path.Length==0)
...{
return false;
}
try
...{
ds.WriteXml(@path,XMLWriteMode.WriteSchema);
return true;
}
catch(Exception e)
...{
Console.WriteLine(e.Message);
return
false;
}
}
}
}