我有一个需要读取excel文件并将其写入sql server的程序。我正在使用IExcelDataReader,只要我有一个工作表,我的代码就可以运行。如果我有另一个例子有一些我不需要插入的信息,我不能具体说明我需要的表格。我知道我应该以某种方式使用NextRecord(),但我无法使其工作。
到目前为止,这是我的代码:
OpenFileDialog ope = new OpenFileDialog();
ope.Filter = "Excel Files|*.xls;*.xlsx;*.xlsm";
if (ope.ShowDialog() == false)
return;
FileStream stream = new FileStream(ope.FileName, FileMode.Open);
IExcelDataReader excelReader = ExcelReaderFactory.CreateOpenXmlReader(stream);
excelReader.IsFirstRowAsColumnNames = true;
DataSet result = excelReader.AsDataSet();
DataClasses1DataContext conn = new DataClasses1DataContext();
foreach (DataTable table in result.Tables)
{
foreach (DataRow dr in dd.Rows)
{
Excel addTable = new Excel()
{
id = Convert.ToInt32(dr[0]),
ime = Convert.ToString(dr[1])
};
conn.ExecuteCommand("TRUNCATE TABLE Excel");
conn.Excels.InsertOnSubmit(addTable);
}
}
conn.SubmitChanges();
excelReader.Close();
stream.Close();
MessageBox.Show("success!");
答案 0 :(得分:0)
我找到了aswer ..在foreach中应该只有:
foreach (DataRow dr in result.Tables[0].Rows)
{
Excel addTable = new Excel()
{
ime = Convert.ToString(dr[1])
};
// conn.ExecuteCommand("TRUNCATE TABLE Excel");
conn.ExecuteCommand("DELETE FROM Excel where ime='a'");
conn.Excels.InsertOnSubmit(addTable);
}