@Spellman.Lau , based on my test, I reproduced your problem. I find that the problem is that the converted datatable will the datatype System.Double after we use OLEDB to read the excel. Therefore, the datatable can not have the type system.string.
For solving the problem, I recommend that you used another method to convert excel to datatable without the above problem.
Please install nuget-package Microsoft.Office.Interop.Excel first.
Then, Please use the following code.
public DataTable READExcel(string path)
{
Microsoft.Office.Interop.Excel.Application objXL = null;
Microsoft.Office.Interop.Excel.Workbook objWB = null;
objXL = new Microsoft.Office.Interop.Excel.Application();
objWB = objXL.Workbooks.Open(path);
Microsoft.Office.Interop.Excel.Worksheet objSHT = objWB.Worksheets[1];
int rows = objSHT.UsedRange.Rows.Count;
int cols = objSHT.UsedRange.Columns.Count;
DataTable dt = new DataTable();
int noofrow = 1;
for (int c = 1; c <= cols; c++)
{
string colname = objSHT.Cells[1, c].Text;
dt.Columns.Add(colname);
noofrow = 2;
}
for (int r = noofrow; r <= rows; r++)
{
DataRow dr = dt.NewRow();
for (int c = 1; c <= cols; c++)
{
dr[c - 1] = objSHT.Cells[r, c].Text;
}
dt.Rows.Add(dr);
}
objWB.Close();
objXL.Quit();
return dt;
}
Finally, you can use the following code to set the format in the datagirview based on the values.
private void Form1_Load(object sender, EventArgs e)
{
DataTable dt = READExcel("D:\\test1.xlsx");
dataGridView1.DataSource = dt;
float f = 0;
int t = 0;
for (int i = 0; i <dataGridView1.Rows.Count-1; i++)
{
string value = dataGridView1.Rows[i].Cells[2].Value.ToString();
if(int.TryParse(value,out t))
{
dataGridView1.Rows[i].Cells[2].Style.Format = "##";
}
else if(float.TryParse(value,out f))
{
dataGridView1.Rows[i].Cells[2].Style.Format = "N3";
}
else
{
dataGridView1.Rows[i].Cells[2].Style.Format = String.Format("c");
}
}
}
Result:
If the response is helpful, please click "Accept Answer" and upvote it.
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.