OpenFileDialog filedialog = new OpenFileDialog();
filedialog.Filter = "Excel文件|*.xls";
if (filedialog.ShowDialog() != DialogResult.OK)
{
return;
}
string filename = filedialog.FileName;
using (FileStream fs = File.OpenRead(filename))
{
IWorkbook workbook = new HSSFWorkbook(fs);
ISheet sheet = workbook.GetSheetAt(0);
string sql = "insert into information values (@cityname,@hotelname,@postion)";
using (SqlConnection conn = new SqlConnection(conStr))
{
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
SqlParameter[] paras = {
new SqlParameter("@cityname",SqlDbType.NVarChar),
new SqlParameter("@hotelname",SqlDbType.NVarChar),
new SqlParameter("@postion",SqlDbType.NVarChar)
};
for (int i = 1; i < sheet.LastRowNum; i++)
{
IRow row = sheet.GetRow(i);
for (int j = 0; j < 3; j++)
{
if (row.GetCell(j) == null)
{
paras[j].Value = "空";
}
else
{
paras[j].Value = row.GetCell(j).ToString();
}
}
cmd.Parameters.AddRange(paras);
conn.Open();
cmd.ExecuteNonQuery();
cmd.Parameters.Clear();//不写这里会报错
conn.Close();
}
}
}
}
MessageBox.Show("OK");
}