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

本文介绍了一种从ListView控件导出数据到Excel的方法,包括创建Excel表、插入数据及文件操作等步骤,并附带了完整的示例代码。

下面代码演示了如何将ListView中的数据导出到Excel的方法,例子代码中还包括了一些编程中的其它小方法,比如:

1)文件的拷贝复制方法

2)文件属性的修改

3)ListView控件Columns的遍历

4)ListView控件Items的遍历

5)foreach语句的使用

6)SaveFileDialog的使用

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文件错误!");
}



}
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值