关于C#导入excel到sql server的问题

qq_35195625 2016-07-11 11:32:39
上星期做的C#导入excel到sql server解决了重复导入信息的问题,加多一个ID列,但是发现导入了第一个excel文件的数据之后第二个导入不了了。求大神指点或解决。
我的winform里只有三个控件:两个botton和一个dataGridView1

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.OleDb;
using System.Data.SqlClient;
using System.Text.RegularExpressions;
using KQ;
using SZCID.Environment;
using SZCID.Environment.Tools;

namespace WindowsFormsApplication59
{
public partial class Form1 : Form
{
string file = null;
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog fileDialog = new OpenFileDialog();
fileDialog.Multiselect = true;
fileDialog.Title = "请选择文件";
fileDialog.Filter = "所有文件(*.*)|*.*";
string fileName = fileDialog.SafeFileName;//获取文件名

if (fileDialog.ShowDialog() == DialogResult.OK)
{
file = fileDialog.FileName;

try
{
using (Excel excelHelper = new Excel(file))
{
DataTable dt = excelHelper.ExcelToDataTable(fileName, true);
dataGridView1.DataSource = dt;
}
}
catch (Exception ex)
{
Console.WriteLine("Exception: " + ex.Message);
}
}
}

private void Form1_Load(object sender, EventArgs e)
{


}

private void button2_Click(object sender, EventArgs e)
{
DataTable dt = new DataTable();
string connstring = "server=.;database=shoucao;uid=zxf; pwd=zxf123";
SqlConnection conn = new SqlConnection(connstring);
conn.Open();
//DataRow dr = null;
if (this.dataGridView1.DataSource != null)
{
int allrow = this.dataGridView1.Rows.Count;//总行数
string zdbh = null;
string jyrqsj = null;
string zzh = null;
string fkh = null;
string jyje = null;
string shfy = null;
string jsje = null;
string xtckh = null;
string xtgzh = null;
string jyqd = null;
string jyle = null;
int id = 0;
//int A = 0;
try
{
for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
zdbh = this.dataGridView1.Rows[i].Cells[0].Value.ToString();
jyrqsj = this.dataGridView1.Rows[i].Cells[1].Value.ToString();
zzh = this.dataGridView1.Rows[i].Cells[2].Value.ToString();
fkh = this.dataGridView1.Rows[i].Cells[3].Value.ToString();
jyje = this.dataGridView1.Rows[i].Cells[4].Value.ToString();
shfy = this.dataGridView1.Rows[i].Cells[5].Value.ToString();
jsje = this.dataGridView1.Rows[i].Cells[6].Value.ToString();
xtckh = this.dataGridView1.Rows[i].Cells[7].Value.ToString();
xtgzh = this.dataGridView1.Rows[i].Cells[8].Value.ToString();
jyqd = this.dataGridView1.Rows[i].Cells[9].Value.ToString();
jyle = this.dataGridView1.Rows[i].Cells[10].Value.ToString();
++id;
string sqlInsert = "insert into dataGridView values('" + id + "','" + zdbh + "','" + jyrqsj + "','" + zzh + "','" + fkh + "','" + jyje + "','" + shfy + "','" + jsje + "','" + xtckh + "','" + xtgzh + "','" + jyqd + "','" + jyle + "')";
SqlCommand cmd = new SqlCommand(sqlInsert, conn);
cmd.ExecuteNonQuery();
}

}

catch (Exception )
{

//MessageBox.Show("Exception: " + ex.Message);

}
}
if (dataGridView1.Rows.Count > 0) //把数据库表中的数据显示到表中,可判断有没有数据
{
MessageBox.Show("导入成功!");
}
else
{
MessageBox.Show("没有数据!");
}
}

private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{

}
}
}

Excel.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Data;
using System.Text.RegularExpressions;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using NPOI.HSSF.UserModel;

namespace KQ
{
class Excel : IDisposable
{
private string fileName = null;
private IWorkbook workbook = null;
private FileStream fs = null;
private bool disposed;

public Excel(string fileName)
{
this.fileName = fileName;
disposed = false;
}
/// <summary>
/// 将excel中的数据导入到DataTable中
/// </summary>
/// <param name="sheetName">excel工作薄sheet的名称</param>
/// <param name="isFirstRowColumn">第一行是否是DataTable的列名</param>
/// <returns>返回的DataTable</returns>
public DataTable ExcelToDataTable(string sheetName, bool isFirstRowColumn)
{
ISheet sheet = null;
DataTable data = new DataTable();
int startRow = 0;
try
{
fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);
if (fileName.IndexOf(".xlsx") > 0) // 2007版本
workbook = new XSSFWorkbook(fs);
else if (fileName.IndexOf(".xls") > 0) // 2003版本
workbook = new HSSFWorkbook(fs);
if (sheetName != null)
{
sheet = workbook.GetSheet(sheetName);
if (sheet == null)
{
sheet = workbook.GetSheetAt(0);//如果没有找到指定的sheetName对应的sheet,则尝试获取第一个sheet
}
}
else
{
sheet = workbook.GetSheetAt(0);
}
//获取并显示设置 列
if (sheet != null)
{
//获取第一行,并设置为列
IRow firstRow = sheet.GetRow(0);
int cellCount = firstRow.LastCellNum;//一行最后一个cell的编号 即总的列数
if (isFirstRowColumn)
{
for (int i = firstRow.FirstCellNum; i < cellCount; ++i)
{
ICell cell = firstRow.GetCell(i);
if (cell != null)
{
string cellValue = cell.StringCellValue;
if (cellValue != null)
{
string[] s = Regex.Replace(cellValue.Trim(), "\\s+", " ").Split(' ');//将多余的空格转成一个空格,然后变成数组
for (int a = 0; a < s.Length; a++)
{
if (s[a].ToString() != null && s[a].ToString().Length != 0)
{
DataColumn column = new DataColumn(s[a]);
data.Columns.Add(column);//赋值到当前行的每一列,直接给dataTable
}
}
}
}
}
startRow = sheet.FirstRowNum + 1;
}
else
{
startRow = sheet.FirstRowNum;
}
//最后一列的标号
//获取每一行的 数据
int rowCount = sheet.LastRowNum;
for (int i = startRow; i <= rowCount; ++i)
{
IRow row = sheet.GetRow(i);
if (row == null) continue; //没有数据的行默认是null       
DataRow dataRow = data.NewRow();
for (int j = row.FirstCellNum; j < cellCount; ++j)
{
if (row.GetCell(j) != null) //同理,没有数据的单元格都默认是null
{
//循环列读取
string[] s = Regex.Replace(row.GetCell(j).StringCellValue, "\\s+", " ").Split(' ');
for (int a = 0; a < s.Length; a++)
{
if (s[a].ToString() != null && s[a].ToString().Length != 0)
{
DataColumn column = new DataColumn(s[a]);
//将当前行的数据 赋给dataRow,然后将dataRow给dataTable
dataRow[a] = column.ToString();
}
}
}
}
data.Rows.Add(dataRow);
}
}
return data;
}
catch (Exception ex)
{
Console.WriteLine("Exception: " + ex.Message);
return null;
}
}
public void Dispose()
{
throw new Exception("The method or operation is not implemented.");
}
}
}
...全文
155 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
qq_35195625 2016-07-11
  • 打赏
  • 举报
回复
把ID列删除了也能导入,但是就是可能重复导入,求大神教
虚云 2016-07-11
  • 打赏
  • 举报
回复
不用加载到DataGridView里,几行代码就可以读取Excel文件,并且不需要第三方组件 DataTable dtResuilt = new DataTable(); string TableName = GetTableName(strExcelFilePath, TableIndex); string strConn = "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" + strExcelFilePath.Trim() + "; Extended Properties=\"Excel 8.0;IMEX=1\""; using (OleDbDataAdapter cmd = new OleDbDataAdapter("SELECT * FROM [" + TableName + "]", strConn)) { cmd.Fill(dtResuilt); return dtResuilt; } 通过上面代码读取到DataTable里,然后循环Row就行了。
大鱼> 2016-07-11
  • 打赏
  • 举报
回复
引用 3 楼 qq_35195625 的回复:
把excel文件读取到C#winform的dataGridView控件里面时候怎么选择只到入自己想要的数据?
你干嘛只要导入想要的数据到DataGridView呢?你的目的是导入到数据库,你可以先把所有的数据导入到DataGridView,然后在DataGridView选中你想导入数据库的数据也行啊?
南天空 2016-07-11
  • 打赏
  • 举报
回复
连接打开后关闭了吗?关闭了重新打开看看。
qq_35195625 2016-07-11
  • 打赏
  • 举报
回复
把excel文件读取到C#winform的dataGridView控件里面时候怎么选择只到入自己想要的数据?
qq_35195625 2016-07-11
  • 打赏
  • 举报
回复
大神都到哪里去了

110,545

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧