private void create_csv(DataTable
dt, string fname)
{
//if
(string.IsNullOrEmpty(fname))
//{
// fname = Application.StartupPath + "\\pdftemplate_"
+ DateTime.Now.Ticks + ".csv";
//}
//else {
fname += ".csv"; } fullfilename = fname;
//FileInfo
f = new FileInfo(fname);
//try
//{
// if (f.Exists)
// {
// f.Delete();
// }
//}
//catch {
f.Delete(); }
fname = GenarateFilename(fname, ".csv");
fullfilename = fname;
FileStream
fs = new FileStream(fname,
FileMode.CreateNew, FileAccess.Write);
StreamWriter
sw = new StreamWriter(fs);
StringBuilder
sb = new StringBuilder();
try
{
//first
line coloumn names
for
(int i = 0; i < dt.Columns.Count; i++)
{
sb.Append("," +
dt.Columns[i].ColumnName.ToString());
}
sw.WriteLine(sb.ToString().Substring(1));
sb.Length = 0;
//
insert datarows in csv file
foreach
(DataRow dr in
dt.Rows)
{
for
(int i = 0; i < dt.Columns.Count; i++)
{
sb.Append("," + dr[i].ToString());
}
sw.WriteLine(sb.ToString().Substring(1));
sb.Length = 0;
}
}
catch
{ }
finally
{
sw.Flush();
sw.Close();
fs.Close();
fs.Dispose();
sb = null;
}
}





0 comments:
Post a Comment