110,538
社区成员
发帖
与我相关
我的任务
分享
public DataTable GetDataFromExcel(String _filename, String _sheetname) // 从Excel里拿到所有行数据
{
try
{
if (_filename == null)
{
FileInfo f = new FileInfo(_filename);
if (!f.Exists)
{
throw new Exception(String.Format("{0} isn't Exist.", f.Name));
}
}
String tbName = String.Empty;
string strConnection = " Provider=Microsoft.Jet.OLEDB.4.0; " +
" Data Source=" + _filename + "; " +
" Extended Properties=Excel 8.0; " +
" Persist Security Info=False";
System.Data.OleDb.OleDbConnection oleConn = new System.Data.OleDb.OleDbConnection(strConnection);
if (oleConn.State == ConnectionState.Closed)
oleConn.Open();
DataTable tables = oleConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new Object[] { null, null, null, "TABLE" });
int cout = 0;
foreach (DataRow dr in tables.Rows)
{
String temp = dr["TABLE_NAME"].ToString();
temp = temp.Substring(0, temp.Length - 1);
if (_sheetname == String.Empty)
{
if (temp.ToLower() == "Sheet1".ToLower())
{
tbName = temp;
break;
}
}
else
{
if (temp.ToLower() == "Sheet1".ToLower())
{
tbName = temp;
}
if (temp.ToLower() == _sheetname.ToLower())
{
tbName = temp;
break;
}
}
++cout;
position = (100 / tables.Rows.Count) * cout;
ProgressEventArgs pe = new ProgressEventArgs(position);
OnProgressChange(pe);
}
if (tbName == String.Empty)
{
throw new Exception("Format of the sheet's name is bad.");
}
String strSql = "SELECT * FROM [" + tbName + "$]";
if (oleConn.State == ConnectionState.Closed)
oleConn.Open();
System.Data.OleDb.OleDbDataAdapter da = new System.Data.OleDb.OleDbDataAdapter(strSql, strConnection);
DataSet ds = new DataSet();
da.Fill(ds, "[" + tbName + "$]");
m_dataTable = ds.Tables[0];
oleConn.Close();
ProgressEventArgs end = new ProgressEventArgs(100);
OnProgressChange(end);
return m_dataTable;
}
catch
{
return null;
}
}
public DataTable GetMyDatatle(DataTable old) //把拿到的DataTable old 拿从第6行起的数据
{
DataTable mytable = new DataTable();
DataColumn dc;
DataRow dr;
for (int i = 0; i < old.Columns.Count; i++)
{
dc = new DataColumn();
dc.ColumnName = old.Columns[i].ColumnName;
mytable.Columns.Add(dc);
}
for (int j = 0; j < old.Rows.Count;j++ )
{
dr = mytable.NewRow();
if (j > 4)
{
for (int k = 0; k < mytable.Columns.Count;k++ )
{
dr[k] = mytable.Rows[j][k].ToString();
}
}
mytable.Rows.Add(dr);
}
return mytable;
}