C#中将ListView中数据导出到Excel的实例方法
2023-06-13 09:14:51 时间
添加方法:选择项目->引用->右击“添加引用”->选择COM找到上面组件—>点击“确定”。
实现代码如下:
privatevoid导出数据_Click(objectsender,EventArgse)
{
ExportToExecl();
}
///<summary>
///执行导出数据
///</summary>
publicvoidExportToExecl()
{
System.Windows.Forms.SaveFileDialogsfd=newSaveFileDialog();
sfd.DefaultExt="xls";
sfd.Filter="Excel文件(*.xls)|*.xls";
if(sfd.ShowDialog()==DialogResult.OK)
{
DoExport(this.lstPostion,sfd.FileName);
}
}
///<summary>
///具体导出的方法
///</summary>
///<paramname="listView">ListView</param>
///<paramname="strFileName">导出到的文件名</param>
privatevoidDoExport(ListViewlistView,stringstrFileName)
{
introwNum=listView.Items.Count;
intcolumnNum=listView.Items[0].SubItems.Count;
introwIndex=1;
intcolumnIndex=0;
if(rowNum==0||string.IsNullOrEmpty(strFileName))
{
return;
}
if(rowNum>0)
{
Microsoft.Office.Interop.Excel.ApplicationxlApp=newMicrosoft.Office.Interop.Excel.ApplicationClass();
if(xlApp==null)
{
MessageBox.Show("无法创建excel对象,可能您的系统没有安装excel");
return;
}
xlApp.DefaultFilePath="";
xlApp.DisplayAlerts=true;
xlApp.SheetsInNewWorkbook=1;
Microsoft.Office.Interop.Excel.WorkbookxlBook=xlApp.Workbooks.Add(true);
//将ListView的列名导入Excel表第一行
foreach(ColumnHeaderdcinlistView.Columns)
{
columnIndex++;
xlApp.Cells[rowIndex,columnIndex]=dc.Text;
}
//将ListView中的数据导入Excel中
for(inti=0;i<rowNum;i++)
{
rowIndex++;
columnIndex=0;
for(intj=0;j<columnNum;j++)
{
columnIndex++;
//注意这个在导出的时候加了“\t”的目的就是避免导出的数据显示为科学计数法。可以放在每行的首尾。
xlApp.Cells[rowIndex,columnIndex]=Convert.ToString(listView.Items[i].SubItems[j].Text)+"\t";
}
}
//例外需要说明的是用strFileName,Excel.XlFileFormat.xlExcel9795保存方式时当你的Excel版本不是95、97而是2003、2007时导出的时候会报一个错误:异常来自HRESULT:0x800A03EC。解决办法就是换成strFileName,Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookNormal。
xlBook.SaveAs(strFileName,Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookNormal,Type.Missing,Type.Missing,Type.Missing,Type.Missing,Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive,Type.Missing,Type.Missing,Type.Missing,Type.Missing,Type.Missing);
xlApp=null;
xlBook=null;
MessageBox.Show("OK");
}
}
相关文章
- excel中html批量转化为pdf文件,如何将大量的Excel转换成PDF?
- csv格式怎么转成excel_比较好一点的Excel转PDF
- c# mysql executenonquery_C#与数据库访问技术之ExecuteNonQuery方法
- C#实现简单网页
- 【地铁上的Redis与C#】数据类型(八)--set类型基本操作
- [问题解决]大数据量上载excel文件数据到SAP系统[ALSM_EXCEL_TO_INTERNAL_TABLE]详解编程语言
- 文件Linux下如何打开Excel文件(linux打开excel)
- MSSQL导入Excel数据的精彩实战(mssql读excel)
- 实现Redis数据批量导出至Excel(redis 转excel)
- 在Asp.net用C#建立动态Excel
- C#可空类型分析
- ADO.NET读取EXCEL的实现代码((c#))
- C#修改MAC地址类的实例
- C#SkinEngine控件给窗体添加皮肤的方法
- 深入C#winform清除由GDI绘制出来的所有线条或图形的解决方法
- C#计算两个文件的相对目录算法的实例代码
- c#日志记录帮助类分享
- c#创建windows服务入门教程实例
- c#+JQurey实现获取radio和checkbox的值
- C#之CLR内存字符串常量池(string)
- C#入门之checked和unchecked的区别实例解析