读取函数
/// <summary>
///
/// </summary>
/// <param name=”filePath”>文件绝对路径</param>
/// <param name=”fileType”>文件类型,xls,xlsx</param>
/// <param name=”Sheet”>工作簿名称,Sheet</param>
/// <param name=”hasTitle”></param>
private void readExcel(string filePath, string fileType, string Sheet, bool hasTitle = false)
{
List<DataListItem> DataList = new List<DataListItem>();
using (DataSet ds = new DataSet())
{
string strCon = string.Format(“Provider=Microsoft.Jet.OLEDB.{0}.0;” +
“Extended Properties=\”Excel {1}.0;HDR={2};IMEX=1;\”;” +
“data source={3};”,
(fileType == “.xls” ? 4 : 12), (fileType == “.xls” ? 8 : 12), (hasTitle ? “Yes” : “NO”), filePath);
string strCom = string.Format(“SELECT * FROM [{0}]”, Sheet);
using (OleDbConnection myConn = new OleDbConnection(strCon))
using (OleDbDataAdapter myCommand = new OleDbDataAdapter(strCom, myConn))
{
myConn.Open();
myCommand.Fill(ds);
}
if (ds != null || ds.Tables.Count > 0)
{
ListViewItem item;
for (int i = 2; i < ds.Tables[0].Rows.Count; i++)
{
item = new ListViewItem();
item.Text = ds.Tables[0].Rows[i][0].ToString();
item.SubItems.Add(ds.Tables[0].Rows[i][1].ToString());
item.SubItems.Add(ds.Tables[0].Rows[i][2].ToString());
item.SubItems.Add(ds.Tables[0].Rows[i][21].ToString());
item.SubItems.Add(ds.Tables[0].Rows[i][22].ToString());
item.SubItems.Add(“等待”);
DataList.Add(
new DataListItem(ds.Tables[0].Rows[i][0].ToString(),
ds.Tables[0].Rows[i][1].ToString(),
ds.Tables[0].Rows[i][2].ToString(),
ds.Tables[0].Rows[i][21].ToString(),
ds.Tables[0].Rows[i][22].ToString()
)
);
}
}
}
自定义类
class DataListItem
{
private string number;
private string signUpId;
private string realName;
private string code;
private string room;
public DataListItem(string Number, string SignUpId, string RealName, string Code, string Room)
{
this.number = Number;
this.signUpId = SignUpId;
this.realName = RealName;
this.code = Code;
this.room = Room;
}
public string Number
{
get { return number; }
set { number = value; }
}
public string SignUpId
{
get { return signUpId; }
set { signUpId = value; }
}
public string RealName
{
get { return realName; }
set { realName = value; }
}
public string Code
{
get { return code; }
set { code = value; }
}
public string Room
{
get { return room; }
set { room = value; }
}
}
声明:
本文采用
BY-NC-SA
协议进行授权,如无注明均为原创,转载请注明转自
一颗大萝北
本文地址: c# 读取Excel内容
本文地址: c# 读取Excel内容