我正在尝试使用WPF应用程序将A系统生成的Excel工作表导入到我的SQL Server表中。问题是Excel工作表的标题写在前4行中,如下所示:
我想做的是:忽略前4行,并从表的列标题开始读取;读取特定的列,而忽略第一列,而读取第二列和第四列。
读取数据后,我想在WPF datagrid中显示它,然后将其导入到SQL Server表中。
任何建议或链接将不胜感激。
答案 0 :(得分:0)
我找到了解决方案,如何跳过行和列
OpenFileDialog openFileDialog = new OpenFileDialog();
openFileDialog.Title = "Test Cases Excel File ..";
if (openFileDialog.ShowDialog() == true)
{
txt_FilePath.Text = openFileDialog.FileName;
Microsoft.Office.Interop.Excel.Application excelApp;
Microsoft.Office.Interop.Excel.Workbook workbook;
Microsoft.Office.Interop.Excel.Worksheet worksheet;
Microsoft.Office.Interop.Excel.Range range;
excelApp = new Microsoft.Office.Interop.Excel.ApplicationClass();
// Opening Excel file
workbook = excelApp.Workbooks.Open(txt_FilePath.Text, 0, true, 5, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
worksheet = (Microsoft.Office.Interop.Excel.Worksheet)workbook.Sheets.get_Item(1);
range = worksheet.UsedRange;
int column = 0;
int row = 0;
System.Data.DataTable dt = new System.Data.DataTable();
dt.Columns.Add("Essential YN");
dt.Columns.Add("Test Area");
dt.Columns.Add("Test Part");
dt.Columns.Add("Test Item");
dt.Columns.Add("Comment");
dt.Columns.Add("Result");
for (row = 5; row <= range.Rows.Count; row++)
{
DataRow dr = dt.NewRow();
for (column = 1; column <= 6; column++)
{
dr[column - 1] = (range.Cells[row, column] as Microsoft.Office.Interop.Excel.Range).Value2.ToString();
}
dt.Rows.Add(dr);
}
workbook.Close();
excelApp.Quit();
// Binding to DataGridView
DataGrid.ItemsSource = dt.DefaultView;