我正在尝试将Excel数据导入SQL Server。以下代码适合我。
但我的问题是它重复了特定列名的数据行。 我们称之为列名'1',在我的存储过程中,我添加了一个参数('01'),它可以过滤掉重复项,即使它不是一个唯一的键列,但它是一个主键不应该完全重复。
我不知道如何使用在C#中插入select语句的参数('01')执行我的存储过程...所以我要做的是,只是添加一个'If语句'比较表'tblname'中的Excel ......这可能吗?
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using Excel;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
namespace RASImportExcelToSql
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog ope = new OpenFileDialog();
ope.Filter = "Excel Files|*.xls;*.xlsx;*.xlsm";
if(ope.ShowDialog() == DialogResult.Cancel)
return;
FileStream stream = new FileStream(ope.FileName,FileMode.Open);
IExcelDataReader excelReader = ExcelReaderFactory.CreateOpenXmlReader(stream);
DataSet result = excelReader.AsDataSet();
DataClasses1DataContext conn = new DataClasses1DataContext();
foreach (DataTable table in result.Tables)
{
foreach (DataRow dr in table.Rows)
{
tblname addtable = new tblname()
{
1 = Convert.ToString(dr[1]),
2 = Convert.ToString(dr[2]),
3 = Convert.ToString(dr[3]),
4 = Convert.ToDateTime(dr[4]),
5 = Convert.ToDecimal(dr[5]),
6 = Convert.ToString(dr[6]),
7 = Convert.ToString(dr[7]),
8 = Convert.ToString(dr[8]),
9 = Convert.ToString(dr[9]),
10 = Convert.ToDateTime(dr[10]),
11 = Convert.ToString(dr[11]),
12 = Convert.ToBoolean(dr[12])
};
conn.tblname.InsertOnSubmit(addtable);
}
}
conn.SubmitChanges();
excelReader.Close();
stream.Close();
MessageBox.Show("Try");
}
}
}
这就是我要做的......
foreach (DataTable table in result.Tables)
{
foreach (DataRow dr in table.Rows)
{
if((1 = Convert.ToString(dr[1)) <> tblname.1)
{
tblname addtable = new tblname()
{
1 = Convert.ToString(dr[1]),
2 = Convert.ToString(dr[2]),
3 = Convert.ToString(dr[3]),
4 = Convert.ToDateTime(dr[4]),
5 = Convert.ToDecimal(dr[5]),
6 = Convert.ToString(dr[6]),
7 = Convert.ToString(dr[7]),
8 = Convert.ToString(dr[8]),
9 = Convert.ToString(dr[9]),
10 = Convert.ToDateTime(dr[10]),
11 = Convert.ToString(dr[11]),
12 = Convert.ToBoolean(dr[12])
};
conn.tblname.InsertOnSubmit(addtable);
}
else
{
MessageBox.Show('None');
}
}
conn.SubmitChanges();
excelReader.Close();
stream.Close();
MessageBox.Show("Try");
}
这可能吗?如果没有,我应该尝试其他什么方法?与此类似的示例代码或链接非常有用。