ListView导出到Excel
来源:互联网 发布:java游戏服务器架构 编辑:程序博客网 时间:2024/06/05 10:28
from:http://limmo.blog.sohu.com/45206198.html
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Windows.Forms;
- using System.Data.OleDb;
- using System.Data;
-
-
- namespace jiayuan.Util
- {
- public static class ListViewToExcel
- {
-
-
-
-
-
-
-
-
-
- public static int ExportToExcel(ListView listView, string destFileName, string tableName)
- {
-
- string szFields = "";
- string szValues = "";
- for (int i = 0; i < listView.Columns.Count; i++)
- {
- szFields += "[" + listView.Columns[i].Text + "],";
- }
- szFields = szFields.TrimEnd(',');
-
- OleDbConnection connection = new OleDbConnection();
- connection.ConnectionString = ListViewToExcel.GetConnectionString(destFileName);
- OleDbCommand command = new OleDbCommand();
- command.Connection = connection;
- command.CommandType = CommandType.Text;
-
- try
- {
- connection.Open();
- }
- catch
- {
- throw new Exception("目标文件路径错误。");
- }
-
- try
- {
- command.CommandText = ListViewToExcel.GetCreateTableSql("[" + tableName + "]", szFields.Split(','));
- command.ExecuteNonQuery();
- }
- catch (Exception ex)
- {
-
- throw ex;
- }
- try
- {
-
- int recordCount = 0;
- for (int i = 0; i < listView.Items.Count; i++)
- {
- szValues = "";
- for (int j = 0; j < listView.Columns.Count; j++)
- {
- if (j >= listView.Items[i].SubItems.Count)
- {
- szValues += "'',";
- }
- else
- {
- szValues += "'" + listView.Items[i].SubItems[j].Text + "',";
- }
- }
- szValues = szValues.TrimEnd(',');
-
- string szSql = "INSERT INTO [" + tableName + "](" + szFields + ") VALUES(" + szValues + ")";
- command.CommandText = szSql;
- recordCount += command.ExecuteNonQuery();
- }
- connection.Close();
- return recordCount;
- }
- catch (Exception ex)
- {
- throw ex;
- }
- }
-
- private static String GetConnectionString(string fullPath)
- {
- string szConnection;
- szConnection = "Provider=Microsoft.JET.OLEDB.4.0;Extended Properties=Excel 8.0;data source=" + fullPath;
- return szConnection;
- }
-
- private static string GetCreateTableSql(string tableName, string[] fields)
- {
- string szSql = "CREATE TABLE " + tableName + "(";
- for (int i = 0; i < fields.Length; i++)
- {
- szSql += fields[i] + " VARCHAR(200),";
- }
- szSql = szSql.TrimEnd(',') + ")";
- return szSql;
- }
-
-
-
-
- }
- }
0 0