如何设置列长度和类型

时间:2014-11-30 15:39:53

标签: c# asp.net excel datatable ado.net

我正在从xls/xlsx个文件中读取DataSet

string connstring;
            if (currFileExtension == ".xlsx")
            {
                connstring = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + currFilePath + ";Extended Properties='Excel 8.0;HDR=NO;IMEX=1';";
            }
            else
            {
                connstring = "Provider=Microsoft.JET.OLEDB.4.0;Data Source=" + currFilePath + ";Extended Properties='Excel 8.0;HDR=NO;IMEX=1';";
            }

            using (OleDbConnection conn = new OleDbConnection(connstring))
            {
                conn.Open();
                DataTable sheetsName = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "Table" });  //Get All Sheets Name
                string firstSheetName = sheetsName.Rows[0][2].ToString();   //Get the First Sheet Name
                string sql = string.Format("SELECT * FROM [{0}]", firstSheetName);  //Query String
                OleDbDataAdapter ada = new OleDbDataAdapter(sql, connstring);
                DataSet set = new DataSet();

                ada.Fill(set);

}

其中一列是字符串,在255个字符后被剪切。

如何在填充DataSet之前设置列? 也许这是一个excel问题,我需要更改excel中的列?

1 个答案:

答案 0 :(得分:4)

您可以将已定义的DataTable添加到DataSet。

这是代码:

DataSet dataSet = new DataSet();

DataTable customTable = new DataTable();
DataColumn dcName = new DataColumn("Name", typeof(string));
dcName.MaxLength= 500;
customTable.Columns.Add(dcName);

dataSet.Tables.Add(customTable);