110,534
社区成员
发帖
与我相关
我的任务
分享
#region 导入Excel数据相关函数
/// <summary>
/// 根据文件名获得Excel的工作薄名称
/// </summary>
/// <param name="excelFileName"></param>
/// <returns></returns>
public static IList<string> GetExcelTablesName(string excelFileName)
{
using (OleDbConnection olbDbConn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source = " + excelFileName + ";Extended Properties = \"Excel 8.0;HDR=YES;IMEX=1;\""))
{
try
{
olbDbConn.Open();
DataTable ExcelTableNames = olbDbConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" });
IList<string> tableList = new List<string>();
foreach (DataRow dr in ExcelTableNames.Rows)
{
tableList.Add((string)dr["TABLE_NAME"]);
}
return tableList;
}
catch (Exception ex)
{
return null;
}
finally
{
olbDbConn.Close();
olbDbConn.Dispose();
}
}
}
/// <summary>
/// 根据文件名、工作薄名称获得数据表
/// </summary>
/// <param name="excelFileName"></param>
/// <param name="tablesName"></param>
/// <returns></returns>
public static DataTable GetExcelDataTable(string excelFileName, string tablesName)
{
using (OleDbConnection olbDbConn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source = " + excelFileName + ";Extended Properties = \"Excel 8.0;HDR=YES;IMEX=1;\""))
{
try
{
string sql = "SELECT * FROM [{0}]";
olbDbConn.Open();
OleDbDataAdapter da = new OleDbDataAdapter();
System.Data.DataSet ds = new System.Data.DataSet();
DataTable dtExcelData = null;
da.SelectCommand = new OleDbCommand(string.Format(sql, tablesName), olbDbConn);
da.Fill(ds, tablesName);
return ds.Tables[tablesName];
}
catch (Exception ex)
{
return null;
}
finally
{
olbDbConn.Close();
olbDbConn.Dispose();
}
}
}
public static void ResetColumnTypeByString(DataTable dt, string columnName)
{
string TempColumnName = "temp";
if (dt.Columns.Contains(columnName) && dt.Columns[columnName].DataType != Type.GetType("System.String"))
{
dt.Columns.Add(TempColumnName, Type.GetType("System.String"));
try
{
foreach (DataRow dr in dt.Rows)
{
dr[TempColumnName] = dr[columnName].ToString();
}
dt.Columns.Remove(columnName);
dt.Columns[TempColumnName].ColumnName = columnName;
}
catch (Exception ex)
{
dt.Columns.Remove(TempColumnName);
throw ex;
}
}
}
#endregion
上面是导入,然后对DataTable循环遍历
foreach(DataRow in dt.rows)
{
string str = string.empty;//临时存放文件夹路径
for(int i=0;i<dt.columns;i++)
{
str = str + dr[i].tostring();
按顺序取第i列,然后看有没有存在该文件夹
如果没有则新建
如果有则跳过
}
}
判断文件夹存在与否你应该会吧,建议文件夹呢?