吴义法

导航

DataGridView 导出 Excel

最近在做一个DataGridView 导出 Excel。在网上搜索一番。有三种方法:

1  直接给Microsoft.Office.Interop.Excel.Workbook.Cells 赋值,这个会报一个excel com组件的一个异常“异常来自 HRESULT:0x800A03EC” 不推荐。

2  使用OdbcCommand 直接使用写入Excel .同样也是报一个ODBC 的错误"ERROR [HY000] [Microsoft][ODBC Excel Driver] Operation must use an updateable query." 不推荐。

3  使用Stream。强烈推进。

datagridview导出Excel(以流的方式)
/// <summary>
/// datagridview导出Excel(以流的方式)
/// </summary>
private void ExportToExcel(DataGridView dgvGF_IN_INFO)
{
SaveFileDialog saveFileDialog
= new SaveFileDialog();
saveFileDialog.Filter
= "Execl files (*.xls)|*.xls";
saveFileDialog.FilterIndex
= 0;
saveFileDialog.RestoreDirectory
= true;
saveFileDialog.CreatePrompt
= true;
saveFileDialog.Title
= "保存为Excel文件";
saveFileDialog.ShowDialog();

if (saveFileDialog.FileName.IndexOf(":") < 0) return; //被点了"取消"

Stream myStream;
myStream
= saveFileDialog.OpenFile();
StreamWriter sw
= new StreamWriter(myStream, System.Text.Encoding.GetEncoding(-0));
string columnTitle = "";
try
{
//写入列标题
for (int i = 0; i < dgvGF_IN_INFO.ColumnCount; i++)
{
if (i > 0)
{
columnTitle
+= "\t";
}
columnTitle
+= dgvGF_IN_INFO.Columns[i].HeaderText;
}
sw.WriteLine(columnTitle);

//写入列内容
for (int j = 0; j < dgvGF_IN_INFO.Rows.Count; j++)
{
string columnValue = "";
for (int k = 0; k < dgvGF_IN_INFO.Columns.Count; k++)
{
if (k > 0)
{
columnValue
+= "\t";
}
if (dgvGF_IN_INFO.Rows[j].Cells[k].Value == null)
columnValue
+= "";
else
columnValue
+= dgvGF_IN_INFO.Rows[j].Cells[k].Value.ToString().Trim();
}
sw.WriteLine(columnValue);
}
sw.Close();
myStream.Close();
}
catch (Exception e)
{
MessageBox.Show(e.ToString());
}
finally
{
sw.Close();
myStream.Close();
}
}

还有比较推荐的参考有:

1 datagridview导出Excel(以流的方式)
http://www.cnblogs.com/perfect/archive/2008/05/05/1183205.html
http://www.yongfa365.com/Item/DataGridViewToExcel.html

2 excel导入datagridwiew

http://www.cnblogs.com/lhxhappy/archive/2008/11/26/1341873.html

posted on 2010-03-27 11:22  吴义法  阅读(621)  评论(2编辑  收藏  举报