Excel到dataTable

时间:2011-02-09 07:49:55

标签: excel

我需要从excel将数据表提取到数据表。我首先尝试使用LinqToExcel库,但是这会从excel表中获取大数字作为指数数字。我说的是像“2352143523453452334544”这样的大数字。只有将它们格式化为文本才能正常工作。 在那之后我尝试了这个:

OleDbConnection con = null;
System.Data.DataTable dt = null;
System.Data.DataTable dataTable1 = new System.Data.DataTable();
string conStr = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + UploadFileName + ";Extended Properties=Excel 8.0;";
string sql_xls;
con = new OleDbConnection(conStr);
con.Open();

//OracleDataAdapter oda = new OracleDataAdapter();
//OracleCommand cmd = new OracleCommand("select * from [Sheet1$]", con);

dt = con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
string[] excelSheetNames = new string[dt.Rows.Count];
int i = 0;
foreach (System.Data.DataRow row in dt.Rows)
{
    excelSheetNames[i] = row["TABLE_NAME"].ToString(); i++;

}

sql_xls = "SELECT * FROM [" + excelSheetNames[0] + "]";
OleDbDataAdapter dataAdapter = new OleDbDataAdapter(sql_xls, conStr);
System.Data.DataSet myDataSet = new System.Data.DataSet();
dataAdapter.Fill(myDataSet, "ExcelInfo");
dataTable1 = myDataSet.Tables["ExcelInfo"];

这个值在与null相同的条件下返回相同的值。 是否有一种从excel文件中获取数据的简单方法?没有转变,没有任何改变。把它全部作为一个字符串,并将其放入数据表?

1 个答案:

答案 0 :(得分:1)

这是我用过的,它对我有用:

private DataTable LoadXLS(string strFile, String sheetName)
    {
        DataTable dtXLS = new DataTable(sheetName);

        try
        {
            string strConnectionString = "";

            if(strFile.Trim().EndsWith(".xlsx"))
            {
                strConnectionString = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=\"Excel 12.0 Xml;HDR=YES;IMEX=1\";", strFile);
            }
            else if(strFile.Trim().EndsWith(".xls")) 
            {
                strConnectionString = string.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=1\";", strFile);
            }

            OleDbConnection SQLConn = new OleDbConnection(strConnectionString);
            SQLConn.Open();

            OleDbDataAdapter SQLAdapter = new OleDbDataAdapter();
            string sql = "SELECT * FROM [" + sheetName + "$]";

            OleDbCommand selectCMD = new OleDbCommand(sql, SQLConn);
            SQLAdapter.SelectCommand = selectCMD;

            SQLAdapter.Fill(dtXLS);
            SQLConn.Close();
        }
        catch (Exception)
        {
            throw;
        }

        return dtXLS;
    }

但您也可以尝试导出为CSV: LinqToCSV