我有这段代码将我从excel文件中复制的内容插入到我的datagridview中,在那里我继续插入(批量插入)到我的数据库中。 我的问题是,当我粘贴到我的datagridview时,第一行变为(并且超过)我的列名,我不确定为什么: 代码如下:
private void btnBulkAdd_Click(object sender, EventArgs e)
{
DataObject o = (DataObject)Clipboard.GetDataObject();
if (o.GetDataPresent(DataFormats.Text))
{
if (dgvIntake.RowCount > 0)
dgvIntake.Rows.Clear();
if (dgvIntake.ColumnCount > 0)
dgvIntake.Columns.Clear();
bool columnsAdded = false;
string[] pastedRows = System.Text.RegularExpressions.Regex.Split(o.GetData(DataFormats.Text).ToString().TrimEnd("\r\n".ToCharArray()), "\r\n");
int j = 0;
foreach (string pastedRow in pastedRows)
{
string[] pastedRowCells = pastedRow.Split(new char[] { '\t' });
if (!columnsAdded)
{
for (int i = 0; i < pastedRowCells.Length; i++)
dgvIntake.Columns.Add("col" + i, pastedRowCells[i]);
columnsAdded = true;
continue;
}
dgvIntake.Rows.Add();
int myRowIndex = dgvIntake.Rows.Count + 1;
using (DataGridViewRow myDataGridViewRow = dgvIntake.Rows[j])
{
for (int i = 0; i < pastedRowCells.Length; i++)
myDataGridViewRow.Cells[i].Value = pastedRowCells[i];
}
j++;
}
}
}
至于我的批量插入按钮:
private void btnBulkInsert_Click(object sender, EventArgs e)
{
string strQuery;
try
{
using (SqlConnection conn = new SqlConnection("Data Source = ROTIMSQL01; Initial Catalog = TDB; Persist Security Info = True; User ID = adiM; Password = Mohan@1234"))
{
using (SqlCommand comm = new SqlCommand())
{
comm.Connection = conn;
conn.Open();
for(int i=0;i<dgvIntake.Rows.Count; i++)
{
strQuery = @"INSERT INTO [dbo].[TestTable] VALUES " + dgvIntake.Rows[i].Cells["ID"].Value + ","
+ dgvIntake.Rows[i].Cells["Other1"].Value + ",'" + dgvIntake.Rows[i].Cells["Other2"].Value + "'," + dgvIntake.Rows[i].Cells["Other3"].Value + ","
+ dgvIntake.Rows[i].Cells["Other4"].Value + "," + dgvIntake.Rows[i].Cells["Other5"].Value + ")";
comm.CommandText = strQuery;
comm.ExecuteNonQuery();
}
}
}
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
我做错了什么? 提前谢谢!
答案 0 :(得分:0)
在Excel上,它不存在'columnname',你在excel中看到的是'values'TOO 。
excel中唯一的列名称如A,B,C,D,E .... Z,AA,AB,AC ......
所以这是正常的,然后你在第一行粘贴了列名。
所以两个解决方案:
可能需要对第一行中的列名进行控制。
在Excel中不应复制列名。