面代碼演示了如何將ListView中的數據導出到Excel的方法,例子代碼中還包括了一些編程中的其它小方法,比如:
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文件錯誤!
"
);
}
}
1)文件的拷貝復制方法
2)文件屬性的修改
3)ListView控件Columns的遍歷
4)ListView控件Items的遍歷
5)foreach語句的使用
6)SaveFileDialog的使用







































































更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
