----------------------
Windows Phone 7手机开发、
.Net培训、期待与您交流! ----------------------
最近做程序时候,做了个EXECL文件导出的功能,今天和大家分享下。在做EXECL导出功能时候,首先,需要引用关于EXECL文件操作类Microsoft Excel 11.0 Object Library以及引用IO流操作类,下面是代码以及注释,提供给各位参考:
try
{
string Path = Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + @"\" + DateTime.Now.ToString() + new Random(DateTime.Now.Millisecond).Next(10000).ToString() + ".xls";
FileStream fs = new FileStream(Path, FileMode.Create, FileAccess.Write);
StreamWriter sw = new StreamWriter(fs, System.Text.Encoding.GetEncoding("GB2312"));
string Line = "";
//输出dataGridView中的行头内容到EXECL文档中
for (int i = 1; i < dataGridView3.Columns.Count; i++)
{
line += dataGridView3.Columns[i].HeaderText + "\t";
}
Sw.WriteLine(line);
//循环输出每行中的单元格内容
for (int j = 0; j < dataGridView3.Rows.Count; j++)
{
line = "";
for (int k = 1; k < dataGridView3.Rows[j].Cells.Count; k++)
{
line += dataGridView3.Rows[j].Cells[k].Value.ToString() + "\t";
}
Sw.WriteLine(line);
}
}
catch (Exception ex)
{
//抛出异常
MessageBox.Show(ex.ToString());
}
//关闭文件输出 和文件流
Sw.Close();
fs.Close();
{
string Path = Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + @"\" + DateTime.Now.ToString() + new Random(DateTime.Now.Millisecond).Next(10000).ToString() + ".xls";
FileStream fs = new FileStream(Path, FileMode.Create, FileAccess.Write);
StreamWriter sw = new StreamWriter(fs, System.Text.Encoding.GetEncoding("GB2312"));
string Line = "";
//输出dataGridView中的行头内容到EXECL文档中
for (int i = 1; i < dataGridView3.Columns.Count; i++)
{
line += dataGridView3.Columns[i].HeaderText + "\t";
}
Sw.WriteLine(line);
//循环输出每行中的单元格内容
for (int j = 0; j < dataGridView3.Rows.Count; j++)
{
line = "";
for (int k = 1; k < dataGridView3.Rows[j].Cells.Count; k++)
{
line += dataGridView3.Rows[j].Cells[k].Value.ToString() + "\t";
}
Sw.WriteLine(line);
}
}
catch (Exception ex)
{
//抛出异常
MessageBox.Show(ex.ToString());
}
//关闭文件输出 和文件流
Sw.Close();
fs.Close();