简体   繁体   English

如何在 DataGridView 中使用 Excel 标头显示完整的 Excel 数据? 当我将标题放在 OleDB Connection 上时,单元格变为空

[英]How to show complete Excel data with Excel Headers in DataGridView? Cells becomes empty when I put headers on OleDB Connection

I want to view the Excel data with headers inside datagridview.我想在 datagridview 中查看带有标题的 Excel 数据。

I have tried changing HDR=Yes to HDR=No.我尝试将 HDR=Yes 更改为 HDR=No。 It shows all the data but I have headers on the Excel file.它显示了所有数据,但我在 Excel 文件上有标题。

I changed this code:我改变了这段代码:

string pathconn = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filePath + ";Extended Properties=\"Excel 12.0;HDR=No;IMEX=1\";";

To:至:

string pathconn = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filePath + ";Extended Properties=\"Excel 12.0;HDR=No;IMEX=1\";";

This is my Excel data:这是我的 Excel 数据:

I get data with headers with this function.我使用此 function 获取带有标题的数据。

public DataTable importaExcelaDT(string file)
        {

DataTable dt = new DataTable();
DataTable dtExcel = new DataTable();

OleDbCommand cmdExcel = new OleDbCommand();

string cadenaConexion = "provider=Microsoft.ACE.OLEDB.12.0;Data Source='" + file + "';Extended Properties = \"Excel 12.0 Xml;HDR=No;IMEX=1\";";

OleDbConnection olConexion = new OleDbConnection(cadenaConexion);

olConexion.Open();
OleDbDataAdapter oda = new OleDbDataAdapter();
dt = olConexion.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" });
string sheet = dt.Rows[0]["TABLE_NAME"].ToString();

cmdExcel.Connection = olConexion;
cmdExcel.CommandText = "SELECT * FROM [" + sheet + "]"; 

oda.SelectCommand = cmdExcel;
oda.Fill(dtExcel);
olConexion.Close();

olConexion.Dispose();
oda.Dispose();
return dtExcel;
}

You have to put in the column name the text of the first row of the datatable.您必须在列名中输入数据表第一行的文本。 Then delete the row.然后删除该行。

Datatable dtExcel = importaExcelaDT(filePath);

for(int i = 0; i < dtExcel.Columns.Count; i++)
{
    string columnName = dtExcel.Rows[0][i].ToString();
    if (columnName == "") //throws error if column name is empty
        columnName = " ";
    dtExcel.Columns[i].ColumnName = columnName;
}
dtExcel.Rows.RemoveAt(0);

yourDataGridView.DataSource = dtExcel;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM