Search code examples
c#asp.netexceldatatableado.net

How to set column length and type


I'm reading from xls/xlsx files to a 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);

}

One of the columns is string and is getting cut after 255 characters.

How to set the column before I fill the DataSet? Maybe it's a excel problem and I need to change the column in the excel?


Solution

  • You can add defined DataTable to DataSet.

    Here's Code:

    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);