在我的项目中,我必须导入一个Excelfile。类型是.xlsx。文件中有一个包含4列的表格。我必须在此excel文件中添加额外的列。我的问题是,在我的解决方案中,DataGridview具有两次标题文本。而且,每当我再次读取文件时,都会获得带有标题文本的新行。我认为问题出在foreach(row.Cells()中的IXLCell单元)中,但我没有发现错误所在。
try
{
OpenFileDialog OpenDataList = new OpenFileDialog();// Erzeugen einen OpenFileDialog-Objektes
OpenDataList.Title = "Datenpunktliste öffnen"; // Initialisiert den Namen des Fensters
OpenDataList.InitialDirectory = @"C:\Users\AdministratorOSMO\Desktop\Testordner"; // Legt den Default Dateipfad fest
OpenDataList.Filter = "Excel Files|*.xls;*.xlsx"; // Filter für die zur Auswahl stehenden Dateitypen
OpenDataList.FilterIndex = 2;// Legt den Standardfilter beim Öffnen fest
if (OpenDataList.ShowDialog() == DialogResult.OK)//Abfrage ob der ShowDialog mit OK bestätigt wurde
{
string PathName = OpenDataList.FileName;// die Variable pathName wird mit dem Inhalt von Filename initialisiert
using (XLWorkbook workBook = new XLWorkbook(PathName))//Arbeitmappe wird erstellt
{
IXLWorksheet workSheet = workBook.Worksheet(1);//Tabelle 1 der Excel-Datei wird in workSheet geschrieben
DataTable dt = new DataTable();// neuer DataTable dt wird erzeugt
bool firstRow = true;// Boolsche Variable für Erste Reihe ?
foreach (IXLRow row in workSheet.Rows())
{
while (firstRow)
{
foreach (IXLCell cell in row.Cells())
{
dt.Columns.Add(cell.Value.ToString());
}
dt.Columns.Add(new DataColumn("OK", typeof(bool)));
dt.Columns.Add(new DataColumn("Datum", typeof(string)));
firstRow = false;
}
dt.Rows.Add();
int i = 0;
foreach (IXLCell cell in row.Cells())
{
dt.Rows[dt.Rows.Count-1][i] = cell.Value.ToString();
i++;
}
Dgv_Data_List.DataSource = dt;
Dgv_Data_List.ReadOnly = true;
}
}
}
}
catch (Exception ex)
{
MessageBox.Show("Error: " + ex.Message);
}
从第一行设置列标题后,您还将处理与普通数据行相同的行。您可以使用continue
转到下一行来停止该操作。 (此外,下面的最后两行可以在foreach循环之外。)
foreach (IXLRow row in workSheet.Rows())
{
if (firstRow)
{
foreach (IXLCell cell in row.Cells())
{
dt.Columns.Add(cell.Value.ToString());
}
dt.Columns.Add(new DataColumn("OK", typeof(bool)));
dt.Columns.Add(new DataColumn("Datum", typeof(string)));
firstRow = false;
continue; // go to next row
}
dt.Rows.Add();
int i = 0;
foreach (IXLCell cell in row.Cells())
{
dt.Rows[dt.Rows.Count-1][i] = cell.Value.ToString();
i++;
}
}
Dgv_Data_List.DataSource = dt;
Dgv_Data_List.ReadOnly = true;
从第一行设置列标题后,您还将处理与普通数据行相同的行。您可以使用continue
转到下一行来停止该操作。 (此外,下面的最后两行可以在foreach循环之外。)
foreach (IXLRow row in workSheet.Rows())
{
if (firstRow)
{
foreach (IXLCell cell in row.Cells())
{
dt.Columns.Add(cell.Value.ToString());
}
dt.Columns.Add(new DataColumn("OK", typeof(bool)));
dt.Columns.Add(new DataColumn("Datum", typeof(string)));
firstRow = false;
continue; // go to next row
}
dt.Rows.Add();
int i = 0;
foreach (IXLCell cell in row.Cells())
{
dt.Rows[dt.Rows.Count-1][i] = cell.Value.ToString();
i++;
}
}
Dgv_Data_List.DataSource = dt;
Dgv_Data_List.ReadOnly = true;