首先声明C#程序读取Excel文件里的数据是很简单的,下面是将读取Excel中数据的方法,其中一些注意事项如下:
1、连接字符串中参数IMEX的值:
0 is Export mode 1 is Import mode 2 is Linked mode (full update capabilities)IMEX有3个值:当IMEX=2 时,EXCEL文档中同时含有字符型和数字型时,比如第C列有3个值,2个为数值型 123,1个为字符型 ABC,当导入时,页面不报错了,但库里只显示数值型的123,而字符型的ABC则呈现为空值。当IMEX=1时,无上述情况发生,库里可正确呈现123 和ABC。
2、参数HDR的值:
HDR=Yes,这代表第一行是标题,不做为数据使用,如果用HDR=NO,则表示第一行不是标题,做为数据来使用。系统默认的是YES。
3、参数Excel 8.0:
对于Excel 97以上版本都用Excel 8.0。
只要注意以上注意事项,操作Excel文件就像操作关系数据库中的一张表一样简单。下面我写一个简单的例子,大家参照这个简单的例子,写自己所须的代码。谢谢!
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Data.OleDb;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
/// <summary>
/// 默认构造函数.<br></br>
/// 2009-04-13 YJ 定义函数.<br></br>
/// </summary>
public Form1()
{
InitializeComponent();
string opnFileName = Application.StartupPath.Trim() + “\\students.xls”;
string strExcel = "";
string strTableNames = "";
string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + opnFileName + ";Extended Properties=\"Excel 8.0;HDR=YES;IMEX=1\"";
strTableNames = GetExcelTableNames(opnFileName);
label1.Text = "";
label1.Text += strTableNames;
label1.Text += "------";
string[] tableNamesArray = strTableNames.Split(',');
OleDbConnection conn = new OleDbConnection(strConn);
OleDbDataAdapter myCommand = null;
DataSet ds = new DataSet();
try
{
strExcel = "select * from [" + tableNamesArray[0] + "]";
conn.Open();
myCommand = new OleDbDataAdapter(strExcel, strConn);
myCommand.Fill(ds, "dtSource");
if (ds != null)
{
//动态读取所有的数据列
for (int j = 0; j < ds.Tables[0].Columns.Count; j++)
{
label1.Text += ds.Tables[0].Columns[j].ColumnName.ToString();
label1.Text += "---";
}
//动态读取第一个所有的数据行
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
label1.Text += ds.Tables[0].Rows[i]["ID"].ToString();
label1.Text += "---";
label1.Text += ds.Tables[0].Rows[i]["姓名"].ToString();
label1.Text += "---";
label1.Text += ds.Tables[0].Rows[i]["性别"].ToString();
label1.Text += "------";
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
conn.Close();
conn.Dispose();
}
}
/// <summary>
/// 动态读取Excel文件中的工作表.<br></br>
/// 2009-04-13 YJ 定义函数.<br></br>
/// </summary>
/// <param name="excelFileName">要读取的文件全名(包括路径地址)</param>
/// <returns>返回工作表的名称</returns>
public static string GetExcelTableNames(string excelFileName)
{
string tableNames = "";
if (File.Exists(excelFileName))
{
using (OleDbConnection conn = new OleDbConnection("Provider=Microsoft.Jet." + "OLEDB.4.0;Extended Properties=\"Excel 8.0\";Data Source=" + excelFileName))
{
conn.Open();
DataTable dt = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
for (int i = 0; i < dt.Rows.Count; i++)
{
tableNames += dt.Rows[i][2].ToString().Trim() + ",";
}
}
}
return tableNames;
}
}
}