设为首页
优惠IDC
收藏本站
六狼博客
六狼论坛
开启辅助访问
切换到窄版
用户名
Email
自动登录
找回密码
密码
登录
立即注册
只需一步,快速开始
只需一步,快速开始
快捷导航
门户
首页
BBS
云计算
大数据
手机
移动开发android,ios,windows phone,windows mobile
编程
编程技术java,php,python,delphi,ruby,c,c++
前端
WEB前端htmlcss,javascript,jquery,html5
数据库
数据库开发Access,mysql,oracle,sql server,MongoDB
系统
操作系统windows,linux,unix,os,RedHat,tomcat
架构
项目管理
软件设计,架构设计,面向对象,设计模式,项目管理
企业
服务
运维实战
神马
搜索
搜索
热搜:
php
java
python
ruby
hadoop
sphinx
solr
ios
android
windows
centos
本版
帖子
用户
六狼论坛
»
首页
›
编程技术
›
C
›
C# 将ListView数据导出到Excel文本之方法
返回列表
查看:
43
|
回复:
0
C# 将ListView数据导出到Excel文本之方法
[复制链接]
helloyesyes
helloyesyes
当前离线
积分
2850
窥视卡
雷达卡
升级
92.5%
当前用户组为
探花
当前积分为
2850
, 升到下一级还需要 150 点。
932
主题
932
主题
932
主题
探花
探花, 积分 2850, 距离下一级还需 150 积分
探花, 积分 2850, 距离下一级还需 150 积分
积分
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;">
public
void
DealExcelOut()
...
{
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
=
new
OleDbConnection(strconn);
OleDbCommandcmd
=
new
OleDbCommand();
Stringcmdstr;
//
根据ListView创建VPN表
try
...
{
cn.Open();
cmd.Connection
=
cn;
cmdstr
=
"
CreateTableVPN(
"
;
foreach
(ColumnHeaderch
in
listView_Main.Columns)
...
{
cmdstr
+=
ch.Text
+
"
TEXT,
"
;
}
cmdstr
=
cmdstr.Remove(cmdstr.Length
-
1
);
cmdstr
+=
"
)
"
;
cmd.CommandText
=
cmdstr;
cmd.ExecuteNonQuery();
}
catch
(Exception)
...
{
MessageBox.Show(
"
读取Excel模板文件错误!
"
);
}
//
导出数据
try
...
{
long
cols
=
listView_Main.Columns.Count;
foreach
(ListViewItemlvi
in
listView_Main.Items)
...
{
cmdstr
=
"
InsertIntoVPNValues(
"
;
for
(
long
i
=
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文件错误!
"
);
}
}
回复
使用道具
举报
提升卡
置顶卡
沉默卡
喧嚣卡
变色卡
千斤顶
显身卡
返回列表
高级模式
B
Color
Image
Link
Quote
Code
Smilies
您需要登录后才可以回帖
登录
|
立即注册
本版积分规则
发表回复
回帖后跳转到最后一页
Copyright © 2008-2020
六狼论坛
(http://it.6wolf.com) 版权所有 All Rights Reserved.
Powered by
Discuz!
X3.4
京ICP备14020293号-2
本网站内容均收集于互联网,如有问题请联系
QQ:389897944
予以删除
快速回复
返回顶部
返回列表