asp.Net ExcelデータからDataTableへのコードの読み出し

3753 ワード

 
  
///
/// 、 Excel : sheet
///

///
///
/// Table,
public DataTable GetExcelData(string astrFileName)
{
string strSheetName = GetExcelWorkSheets(astrFileName)[0].ToString();
return GetExcelData(astrFileName, strSheetName);
}

コード#コード#
 
  
///
/// ; WorkSheet, ArrayList,
///

/// Excel
/// WorkSheet, ArrayList,
public ArrayList GetExcelWorkSheets(string strFilePath)
{
ArrayList alTables = new ArrayList();
OleDbConnection odn = new OleDbConnection(GetExcelConnection(strFilePath));
odn.Open();
DataTable dt = new DataTable();
dt = odn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
if (dt == null)
{
throw new Exception(" Excel 。");
}
foreach (DataRow dr in dt.Rows)
{
string tempName = dr["Table_Name"].ToString();
int iDolarIndex = tempName.IndexOf('$');
if (iDolarIndex > 0)
{
tempName = tempName.Substring(0, iDolarIndex);
}
// Excel2003 BUG。
if (tempName[0] == '\'')
{
if (tempName[tempName.Length - 1] == '\'')
{
tempName = tempName.Substring(1, tempName.Length - 2);
}
else
{
tempName = tempName.Substring(1, tempName.Length - 1);
}
}
if (!alTables.Contains(tempName))
{
alTables.Add(tempName);
}
}
odn.Close();
if (alTables.Count == 0)
{
return null;
}
return alTables;
}

コード#コード#
 
  
///
/// 、 Excel
///

///
///
/// Table,
public DataTable GetExcelData(string FilePath, string WorkSheetName)
{
DataTable dtExcel = new DataTable();
OleDbConnection con = new OleDbConnection(GetExcelConnection(FilePath));
OleDbDataAdapter adapter = new OleDbDataAdapter("Select * from [" + WorkSheetName + "$]", con);
//
con.Open();
adapter.FillSchema(dtExcel, SchemaType.Mapped);
adapter.Fill(dtExcel);
con.Close();
dtExcel.TableName = WorkSheetName;
//
return dtExcel;
}

コード#コード#
 
  
///
///
///

///
///
public string GetExcelConnection(string strFilePath)
{
if (!File.Exists(strFilePath))
{
throw new Exception(" Excel !");
}
return "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + strFilePath + ";Extended properties=\"Excel 8.0;Imex=1;HDR=Yes;\"";
//@"Provider=Microsoft.Jet.OLEDB.4.0;" +
//@"Data Source=" + strFilePath + ";" +
//@"Extended Properties=" + Convert.ToChar(34).ToString() +
//@"Excel 8.0;" + "Imex=1;HDR=Yes;" + Convert.ToChar(34).ToString();
}