asp.net DataGridView导出到Excel的三个方法[亲测]
程序员文章站
2023-12-25 23:19:45
#region datagridview数据显示到excel /// &n...
#region datagridview数据显示到excel
/// <summary>
/// 打开excel并将datagridview控件中数据导出到excel
/// </summary>
/// <param name="dgv">datagridview对象 </param>
/// <param name="isshowexcle">是否显示excel界面 </param>
/// <remarks>
/// add com "microsoft excel 11.0 object library"
/// using excel=microsoft.office.interop.excel;
/// </remarks>
/// <returns> </returns>
public bool datagridviewshowtoexcel(datagridview dgv, bool isshowexcle)
{
if (dgv.rows.count == 0)
return false;
//建立excel对象
excel.application excel = new excel.application();
excel.application.workbooks.add(true);
excel.visible = isshowexcle;
//生成字段名称
for (int i = 0; i < dgv.columncount; i++)
{
excel.cells[1, i + 1] = dgv.columns[i].headertext;
}
//填充数据
for (int i = 0; i < dgv.rowcount - 1; i++)
{
for (int j = 0; j < dgv.columncount; j++)
{
if (dgv[j, i].valuetype == typeof(string))
{
excel.cells[i + 2, j + 1] = "'" + dgv[j, i].value.tostring();
}
else
{
excel.cells[i + 2, j + 1] = dgv[j, i].value.tostring();
}
}
}
return true;
}
#endregion
#region dategridview导出到csv格式的excel
/// <summary>
/// 常用方法,列之间加\t,一行一行输出,此文件其实是csv文件,不过默认可以当成excel打开。
/// </summary>
/// <remarks>
/// using system.io;
/// </remarks>
/// <param name="dgv"></param>
private void datagridviewtoexcel(datagridview dgv)
{
savefiledialog dlg = new savefiledialog();
dlg.filter = "execl files (*.xls)|*.xls";
dlg.filterindex = 0;
dlg.restoredirectory = true;
dlg.createprompt = true;
dlg.title = "保存为excel文件";
if (dlg.showdialog() == dialogresult.ok)
{
stream mystream;
mystream = dlg.openfile();
streamwriter sw = new streamwriter(mystream, system.text.encoding.getencoding(-0));
string columntitle = "";
try
{
//写入列标题
for (int i = 0; i < dgv.columncount; i++)
{
if (i > 0)
{
columntitle += "\t";
}
columntitle += dgv.columns[i].headertext;
}
sw.writeline(columntitle);
//写入列内容
for (int j = 0; j < dgv.rows.count; j++)
{
string columnvalue = "";
for (int k = 0; k < dgv.columns.count; k++)
{
if (k > 0)
{
columnvalue += "\t";
}
if (dgv.rows[j].cells[k].value == null)
columnvalue += "";
else
columnvalue += dgv.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();
}
}
}
#endregion
#region datagridview导出到excel,有一定的判断性
/// <summary>
///方法,导出datagridview中的数据到excel文件
/// </summary>
/// <remarks>
/// add com "microsoft excel 11.0 object library"
/// using excel=microsoft.office.interop.excel;
/// using system.reflection;
/// </remarks>
/// <param name= "dgv"> datagridview </param>
public static void datagridviewtoexcel(datagridview dgv)
{
#region 验证可操作性
//申明保存对话框
savefiledialog dlg = new savefiledialog();
//默然文件后缀
dlg.defaultext = "xls ";
//文件后缀列表
dlg.filter = "excel文件(*.xls)|*.xls ";
//默然路径是系统当前路径
dlg.initialdirectory = directory.getcurrentdirectory();
//打开保存对话框
if (dlg.showdialog() == dialogresult.cancel) return;
//返回文件路径
string filenamestring = dlg.filename;
//验证strfilename是否为空或值无效
if (filenamestring.trim() == " ")
{ return; }
//定义表格内数据的行数和列数
int rowscount = dgv.rows.count;
int colscount = dgv.columns.count;
//行数必须大于0
if (rowscount <= 0)
{
messagebox.show("没有数据可供保存 ", "提示 ", messageboxbuttons.ok, messageboxicon.information);
return;
}
//列数必须大于0
if (colscount <= 0)
{
messagebox.show("没有数据可供保存 ", "提示 ", messageboxbuttons.ok, messageboxicon.information);
return;
}
//行数不可以大于65536
if (rowscount > 65536)
{
messagebox.show("数据记录数太多(最多不能超过65536条),不能保存 ", "提示 ", messageboxbuttons.ok, messageboxicon.information);
return;
}
//列数不可以大于255
if (colscount > 255)
{
messagebox.show("数据记录行数太多,不能保存 ", "提示 ", messageboxbuttons.ok, messageboxicon.information);
return;
}
//验证以filenamestring命名的文件是否存在,如果存在删除它
fileinfo file = new fileinfo(filenamestring);
if (file.exists)
{
try
{
file.delete();
}
catch (exception error)
{
messagebox.show(error.message, "删除失败 ", messageboxbuttons.ok, messageboxicon.warning);
return;
}
}
#endregion
excel.application objexcel = null;
excel.workbook objworkbook = null;
excel.worksheet objsheet = null;
try
{
//申明对象
objexcel = new microsoft.office.interop.excel.application();
objworkbook = objexcel.workbooks.add(missing.value);
objsheet = (excel.worksheet)objworkbook.activesheet;
//设置excel不可见
objexcel.visible = false;
//向excel中写入表格的表头
int displaycolumnscount = 1;
for (int i = 0; i <= dgv.columncount - 1; i++)
{
if (dgv.columns[i].visible == true)
{
objexcel.cells[1, displaycolumnscount] = dgv.columns[i].headertext.trim();
displaycolumnscount++;
}
}
//设置进度条
//tempprogressbar.refresh();
//tempprogressbar.visible = true;
//tempprogressbar.minimum=1;
//tempprogressbar.maximum=dgv.rowcount;
//tempprogressbar.step=1;
//向excel中逐行逐列写入表格中的数据
for (int row = 0; row <= dgv.rowcount - 1; row++)
{
//tempprogressbar.performstep();
displaycolumnscount = 1;
for (int col = 0; col < colscount; col++)
{
if (dgv.columns[col].visible == true)
{
try
{
objexcel.cells[row + 2, displaycolumnscount] = dgv.rows[row].cells[col].value.tostring().trim();
displaycolumnscount++;
}
catch (exception)
{
}
}
}
}
//隐藏进度条
//tempprogressbar.visible = false;
//保存文件
objworkbook.saveas(filenamestring, missing.value, missing.value, missing.value, missing.value,
missing.value, excel.xlsaveasaccessmode.xlshared, missing.value, missing.value, missing.value,
missing.value, missing.value);
}
catch (exception error)
{
messagebox.show(error.message, "警告 ", messageboxbuttons.ok, messageboxicon.warning);
return;
}
finally
{
//关闭excel应用
if (objworkbook != null) objworkbook.close(missing.value, missing.value, missing.value);
if (objexcel.workbooks != null) objexcel.workbooks.close();
if (objexcel != null) objexcel.quit();
objsheet = null;
objworkbook = null;
objexcel = null;
}
messagebox.show(filenamestring + "\n\n导出完毕! ", "提示 ", messageboxbuttons.ok, messageboxicon.information);
}
#endregion
/// <summary>
/// 打开excel并将datagridview控件中数据导出到excel
/// </summary>
/// <param name="dgv">datagridview对象 </param>
/// <param name="isshowexcle">是否显示excel界面 </param>
/// <remarks>
/// add com "microsoft excel 11.0 object library"
/// using excel=microsoft.office.interop.excel;
/// </remarks>
/// <returns> </returns>
public bool datagridviewshowtoexcel(datagridview dgv, bool isshowexcle)
{
if (dgv.rows.count == 0)
return false;
//建立excel对象
excel.application excel = new excel.application();
excel.application.workbooks.add(true);
excel.visible = isshowexcle;
//生成字段名称
for (int i = 0; i < dgv.columncount; i++)
{
excel.cells[1, i + 1] = dgv.columns[i].headertext;
}
//填充数据
for (int i = 0; i < dgv.rowcount - 1; i++)
{
for (int j = 0; j < dgv.columncount; j++)
{
if (dgv[j, i].valuetype == typeof(string))
{
excel.cells[i + 2, j + 1] = "'" + dgv[j, i].value.tostring();
}
else
{
excel.cells[i + 2, j + 1] = dgv[j, i].value.tostring();
}
}
}
return true;
}
#endregion
#region dategridview导出到csv格式的excel
/// <summary>
/// 常用方法,列之间加\t,一行一行输出,此文件其实是csv文件,不过默认可以当成excel打开。
/// </summary>
/// <remarks>
/// using system.io;
/// </remarks>
/// <param name="dgv"></param>
private void datagridviewtoexcel(datagridview dgv)
{
savefiledialog dlg = new savefiledialog();
dlg.filter = "execl files (*.xls)|*.xls";
dlg.filterindex = 0;
dlg.restoredirectory = true;
dlg.createprompt = true;
dlg.title = "保存为excel文件";
if (dlg.showdialog() == dialogresult.ok)
{
stream mystream;
mystream = dlg.openfile();
streamwriter sw = new streamwriter(mystream, system.text.encoding.getencoding(-0));
string columntitle = "";
try
{
//写入列标题
for (int i = 0; i < dgv.columncount; i++)
{
if (i > 0)
{
columntitle += "\t";
}
columntitle += dgv.columns[i].headertext;
}
sw.writeline(columntitle);
//写入列内容
for (int j = 0; j < dgv.rows.count; j++)
{
string columnvalue = "";
for (int k = 0; k < dgv.columns.count; k++)
{
if (k > 0)
{
columnvalue += "\t";
}
if (dgv.rows[j].cells[k].value == null)
columnvalue += "";
else
columnvalue += dgv.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();
}
}
}
#endregion
#region datagridview导出到excel,有一定的判断性
/// <summary>
///方法,导出datagridview中的数据到excel文件
/// </summary>
/// <remarks>
/// add com "microsoft excel 11.0 object library"
/// using excel=microsoft.office.interop.excel;
/// using system.reflection;
/// </remarks>
/// <param name= "dgv"> datagridview </param>
public static void datagridviewtoexcel(datagridview dgv)
{
#region 验证可操作性
//申明保存对话框
savefiledialog dlg = new savefiledialog();
//默然文件后缀
dlg.defaultext = "xls ";
//文件后缀列表
dlg.filter = "excel文件(*.xls)|*.xls ";
//默然路径是系统当前路径
dlg.initialdirectory = directory.getcurrentdirectory();
//打开保存对话框
if (dlg.showdialog() == dialogresult.cancel) return;
//返回文件路径
string filenamestring = dlg.filename;
//验证strfilename是否为空或值无效
if (filenamestring.trim() == " ")
{ return; }
//定义表格内数据的行数和列数
int rowscount = dgv.rows.count;
int colscount = dgv.columns.count;
//行数必须大于0
if (rowscount <= 0)
{
messagebox.show("没有数据可供保存 ", "提示 ", messageboxbuttons.ok, messageboxicon.information);
return;
}
//列数必须大于0
if (colscount <= 0)
{
messagebox.show("没有数据可供保存 ", "提示 ", messageboxbuttons.ok, messageboxicon.information);
return;
}
//行数不可以大于65536
if (rowscount > 65536)
{
messagebox.show("数据记录数太多(最多不能超过65536条),不能保存 ", "提示 ", messageboxbuttons.ok, messageboxicon.information);
return;
}
//列数不可以大于255
if (colscount > 255)
{
messagebox.show("数据记录行数太多,不能保存 ", "提示 ", messageboxbuttons.ok, messageboxicon.information);
return;
}
//验证以filenamestring命名的文件是否存在,如果存在删除它
fileinfo file = new fileinfo(filenamestring);
if (file.exists)
{
try
{
file.delete();
}
catch (exception error)
{
messagebox.show(error.message, "删除失败 ", messageboxbuttons.ok, messageboxicon.warning);
return;
}
}
#endregion
excel.application objexcel = null;
excel.workbook objworkbook = null;
excel.worksheet objsheet = null;
try
{
//申明对象
objexcel = new microsoft.office.interop.excel.application();
objworkbook = objexcel.workbooks.add(missing.value);
objsheet = (excel.worksheet)objworkbook.activesheet;
//设置excel不可见
objexcel.visible = false;
//向excel中写入表格的表头
int displaycolumnscount = 1;
for (int i = 0; i <= dgv.columncount - 1; i++)
{
if (dgv.columns[i].visible == true)
{
objexcel.cells[1, displaycolumnscount] = dgv.columns[i].headertext.trim();
displaycolumnscount++;
}
}
//设置进度条
//tempprogressbar.refresh();
//tempprogressbar.visible = true;
//tempprogressbar.minimum=1;
//tempprogressbar.maximum=dgv.rowcount;
//tempprogressbar.step=1;
//向excel中逐行逐列写入表格中的数据
for (int row = 0; row <= dgv.rowcount - 1; row++)
{
//tempprogressbar.performstep();
displaycolumnscount = 1;
for (int col = 0; col < colscount; col++)
{
if (dgv.columns[col].visible == true)
{
try
{
objexcel.cells[row + 2, displaycolumnscount] = dgv.rows[row].cells[col].value.tostring().trim();
displaycolumnscount++;
}
catch (exception)
{
}
}
}
}
//隐藏进度条
//tempprogressbar.visible = false;
//保存文件
objworkbook.saveas(filenamestring, missing.value, missing.value, missing.value, missing.value,
missing.value, excel.xlsaveasaccessmode.xlshared, missing.value, missing.value, missing.value,
missing.value, missing.value);
}
catch (exception error)
{
messagebox.show(error.message, "警告 ", messageboxbuttons.ok, messageboxicon.warning);
return;
}
finally
{
//关闭excel应用
if (objworkbook != null) objworkbook.close(missing.value, missing.value, missing.value);
if (objexcel.workbooks != null) objexcel.workbooks.close();
if (objexcel != null) objexcel.quit();
objsheet = null;
objworkbook = null;
objexcel = null;
}
messagebox.show(filenamestring + "\n\n导出完毕! ", "提示 ", messageboxbuttons.ok, messageboxicon.information);
}
#endregion