第一个:
using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.OleDb;
using Microsoft.Office.Interop.Excel;
namespace Newpro
{
public class Excel
{
///
/// 导出全部的信息
///
///
//传递一个ListView控件
///Excel的标题
public void OperateExcel(System.Windows.Forms.ListView list)//FileTitle为些Excel的标题
{
//实例化出Excel对象
try
{
Application excel = new Application();
//开启Excel
excel.Application.Workbooks.Add(true);
int rowCount = list.Items.Count;
int colCount = list.Columns.Count;
object[,] dataArray = new object[rowCount + 1, colCount];
for (int k = 0; k < colCount; k++)
{
dataArray[0, k] = list.Columns[k].Text;
}
if (list.Items.Count != 0)
{
for (int i = 0; i < rowCount; i++)
{
for (int j = 0; j < colCount; j++)
{
dataArray[i + 1, j] = list.Items[i].SubItems[j].Text;
}
}
}
//填充Excel
excel.get_Range("A1", excel.Cells[rowCount + 1, colCount]).Value2 = dataArray;
//显示Excel
excel.Visible = true;
}
catch (Exception ex)
{
System.Windows.Forms.MessageBox.Show(ex.Message);
}
}
///
/// 读取Excel文档
///
///
/// 返回一个数据集
//文件名称
public System.Data.DataTable ExcelToDS(string Path)
{
try
{
string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + Path + ";" + "Extended Properties=Excel 8.0;";
OleDbConnection conn = new OleDbConnection(strConn);
conn.Open();
string strExcel = "";
OleDbDataAdapter myCommand = null;
strExcel = "select * from [Sheet1$]";
myCommand = new OleDbDataAdapter(strExcel, strConn);
System.Data.DataTable dt = new System.Data.DataTable();
myCommand.Fill(dt);
return dt;
}
catch (Exception ex)
{
System.Windows.Forms.MessageBox.Show(ex.Message);
return new System.Data.DataTable();
}
}
}
}