面代碼演示了如何將ListView中的數(shù)據(jù)導(dǎo)出到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;
//
根據(jù)ListView創(chuàng)建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模板文件錯(cuò)誤!
"
);
}
//
導(dǎo)出數(shù)據(jù)
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對(duì)話框,復(fù)制臨時(shí)文件到指定文件
DialogResultr
=
saveFileDialog_Excel.ShowDialog();
if
(r
==
DialogResult.OK)
{
File.Copy(path2,saveFileDialog_Excel.FileName,
true
);
}
File.Delete(path2);
}
catch
(Exception)
{
MessageBox.Show(
"
訪問(wèn)Excel文件錯(cuò)誤!
"
);
}
}
1)文件的拷貝復(fù)制方法
2)文件屬性的修改
3)ListView控件Columns的遍歷
4)ListView控件Items的遍歷
5)foreach語(yǔ)句的使用
6)SaveFileDialog的使用







































































更多文章、技術(shù)交流、商務(wù)合作、聯(lián)系博主
微信掃碼或搜索:z360901061

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