六狼论坛

 找回密码
 立即注册

QQ登录

只需一步,快速开始

新浪微博账号登陆

只需一步,快速开始

搜索
查看: 43|回复: 0

C# 将ListView数据导出到Excel文本之方法

[复制链接]

升级  92.5%

932

主题

932

主题

932

主题

探花

Rank: 6Rank: 6

积分
2850
 楼主| 发表于 2013-2-1 09:51:43 | 显示全部楼层 |阅读模式
下面代码演示了如何将ListView中的数据导出到Excel的方法,例子代码中还包括了一些编程中的其它小方法,比如:
1)文件的拷贝复制方法
2)文件属性的修改
3)ListView控件Columns的遍历
4)ListView控件Items的遍历
5)foreach语句的使用
6)SaveFileDialog的使用
<div style="padding-right: 5.4pt; padding-left: 5.4pt; background: #e6e6e6; padding-bottom: 4px; width: 95%; padding-top: 4px;">publicvoidDealExcelOut()
...{
Stringpath
=Application.StartupPath;
Stringpath1
=path+"\tmp.xls";
Stringpath2
=path+"\tmp2.xls";
File.Copy(path1,path2,
true);
File.SetAttributes(path2,FileAttributes.Normal);

Stringstrconn
="Provider=Microsoft.jet.OLEDB.4.0;DataSource="+path2+";ExtendedProperties=Excel8.0";
OleDbConnectioncn
=newOleDbConnection(strconn);
OleDbCommandcmd
=newOleDbCommand();
Stringcmdstr;

//根据ListView创建VPN表
try
...{
cn.Open();
cmd.Connection
=cn;

cmdstr
="CreateTableVPN(";
foreach(ColumnHeaderchinlistView_Main.Columns)
...{
cmdstr
+=ch.Text+"TEXT,";
}


cmdstr
=cmdstr.Remove(cmdstr.Length-1);
cmdstr
+=")";
cmd.CommandText
=cmdstr;
cmd.ExecuteNonQuery();

}

catch(Exception)
...{
MessageBox.Show(
"读取Excel模板文件错误!");
}


//导出数据
try
...{
longcols=listView_Main.Columns.Count;

foreach(ListViewItemlviinlistView_Main.Items)
...{
cmdstr
="InsertIntoVPNValues(";
for(longi=0;i<cols;i++)
cmdstr
+="'"+lvi.SubItems[(Int32)i].Text+"',";

cmdstr
=cmdstr.Remove(cmdstr.Length-1);
cmdstr
+=")";
cmd.CommandText
=cmdstr;
cmd.ExecuteNonQuery();
}


cn.Close();

//显示FileSave对话框,复制临时文件到指定文件
DialogResultr=saveFileDialog_Excel.ShowDialog();
if(r==DialogResult.OK)
...{
File.Copy(path2,saveFileDialog_Excel.FileName,
true);
}


File.Delete(path2);
}

catch(Exception)
...{
MessageBox.Show(
"访问Excel文件错误!");
}



}
您需要登录后才可以回帖 登录 | 立即注册 新浪微博账号登陆

本版积分规则

快速回复 返回顶部 返回列表