手机
当前位置:查字典教程网 >编程开发 >C#教程 >C#中将ListView中数据导出到Excel的实例方法
C#中将ListView中数据导出到Excel的实例方法
摘要:添加方法:选择项目->引用->右击“添加引用”->选择COM找到上面组件—>点击“确定”。实现代码如下:复制代码代码如下:privatevo...

添加方法:选择项目->引用->右击“添加引用”->选择COM 找到上面组件—>点击“确定”。

实现代码如下:

复制代码 代码如下:

private void 导出数据_Click(object sender, EventArgs e)

{

ExportToExecl();

}

/// <summary>

/// 执行导出数据

/// </summary>

public void ExportToExecl()

{

System.Windows.Forms.SaveFileDialog sfd = new SaveFileDialog();

sfd.DefaultExt = "xls";

sfd.Filter = "Excel文件(*.xls)|*.xls";

if (sfd.ShowDialog() == DialogResult.OK)

{

DoExport(this.lstPostion, sfd.FileName);

}

}

/// <summary>

/// 具体导出的方法

/// </summary>

/// <param name="listView">ListView</param>

/// <param name="strFileName">导出到的文件名</param>

private void DoExport(ListView listView, string strFileName)

{

int rowNum = listView.Items.Count;

int columnNum = listView.Items[0].SubItems.Count;

int rowIndex = 1;

int columnIndex = 0;

if (rowNum == 0 || string.IsNullOrEmpty(strFileName))

{

return;

}

if (rowNum > 0)

{

Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.ApplicationClass();

if (xlApp == null)

{

MessageBox.Show("无法创建excel对象,可能您的系统没有安装excel");

return;

}

xlApp.DefaultFilePath = "";

xlApp.DisplayAlerts = true;

xlApp.SheetsInNewWorkbook = 1;

Microsoft.Office.Interop.Excel.Workbook xlBook = xlApp.Workbooks.Add(true);

//将ListView的列名导入Excel表第一行

foreach (ColumnHeader dc in listView.Columns)

{

columnIndex++;

xlApp.Cells[rowIndex, columnIndex] = dc.Text;

}

//将ListView中的数据导入Excel中

for (int i = 0; i < rowNum; i++)

{

rowIndex++;

columnIndex = 0;

for (int j = 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");

}

}

【C#中将ListView中数据导出到Excel的实例方法】相关文章:

c# 获取数据库中所有表名称的方法

c#数据库与TXT导入导出的实例

C#从实体对象集合中导出Excel的代码

c#中虚函数的相关使用方法

C# 合并GriewView相同列的小例子

C# 将字节流转换为图片的实例方法

C#操作EXCEL DataTable转换的实例代码

C#连接Oracle数据库的实例方法

C#中Web.Config加密与解密的方法

C#中Array与ArrayList用法及转换的方法

精品推荐
分类导航