将文本文件导入DataGrid,然后保存到数据库
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了将文本文件导入DataGrid,然后保存到数据库相关的知识,希望对你有一定的参考价值。
我想将文本文件导入Datagrid,当我单击Save时,它会将表保存到数据库。
我试过这段代码。但它说“找不到第3栏”。
private void btnImport_Click(object sender, EventArgs e)
{
try
{
string line;
DataTable table = new DataTable();
table.Columns.Add("Employee ID");
table.Columns.Add("Time Stamp");
table.Columns.Add("Attendance Code");
using (System.IO.FileStream stream = System.IO.File.OpenRead(textEditExcel.Text))
{
using (System.IO.StreamReader sr = new System.IO.StreamReader(stream))
{
while ((line = sr.ReadLine()) != null)
{
string[] parts = line.Split(' ');
var dr = table.NewRow();
for (int i = 0; i < parts.Length; i++)
{
dr[i] = parts[i];
}
table.Rows.Add(dr);
}
sr.Close();
}
}
dgMain.DataSource = table;
this.Controls.Add(dgMain);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
MessageBox.Show("Something went wrong! File not imported.");
}
}
答案
问题是你的数据表有三列但你的文本文件有六列,所以当你的代码
for (int i = 0; i < parts.Length; i++)
{
dr[i] = parts[i];
}
有效说:
dr[0] = parts[0];
dr[1] = parts[1];
dr[2] = parts[2];
dr[3] = parts[3]; // this fails because there is no dr[3]
dr[4] = parts[4];
dr[5] = parts[5];
你可以暴力破坏田地:
string[] parts = line.Split(' ');
var dr = table.NewRow();
dr[0] = parts[0];
dr[1] = parts[1];
dr[2] = parts[2] + parts[3] + parts[4] + parts[5];
或者,如果你想要一些更具可扩展性或更聪明的东西,这也可以:
dr[2] = string.Join(string.Empty, parts.Skip(2).Take(4));
另一答案
我自己想出来了,这就是答案:
string[] parts = line.Split(' ');
var dr = dt.NewRow();
dr["EmployeeID"] = parts[0].Trim();
dr["Timestamp"] = parts[1].Trim();
dr["AttendanceCode"] = parts[2].Trim() + parts[3].Trim() + parts[4].Trim() + parts[5].Trim();
dt.Rows.Add(dr);
另一答案
下面的代码应该涵盖一切。
Imports System.Data.SqlClient
Imports System.IO
Imports Microsoft.VisualBasic.FileIO
Imports System.Data
Imports System.Data.Odbc
Imports System.Data.OleDb
Public Class Form1
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
Dim headers = (From header As DataGridViewColumn In DataGridView1.Columns.Cast(Of DataGridViewColumn)() Select header.HeaderText).ToArray
Dim rows = From row As DataGridViewRow In DataGridView1.Rows.Cast(Of DataGridViewRow)() Where Not row.IsNewRow Select Array.ConvertAll(row.Cells.Cast(Of DataGridViewCell).ToArray, Function(c) If(c.Value IsNot Nothing, c.Value.ToString, ""))
Dim str As String = ""
Using sw As New IO.StreamWriter("C:UsersExcelDesktopOrdersTest.csv")
sw.WriteLine(String.Join(",", headers))
'sw.WriteLine(String.Join(","))
For Each r In rows
sw.WriteLine(String.Join(",", r))
Next
sw.Close()
End Using
End Sub
Private Sub Button2_Click(sender As System.Object, e As System.EventArgs) Handles Button2.Click
'Dim m_strConnection As String = "server=Excel-PCSQLEXPRESS;Initial Catalog=Northwind;Trusted_Connection=True;"
'Catch ex As Exception
' MessageBox.Show(ex.ToString())
'End Try
'Dim objDataset1 As DataSet()
'Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
'Dim da As OdbcDataAdapter
Dim OpenFile As New System.Windows.Forms.OpenFileDialog ' Does something w/ the OpenFileDialog
Dim strFullPath As String, strFileName As String
Dim tbFile As New TextBox
' Sets some OpenFileDialog box options
OpenFile.Filter = "CSV Files (*.csv)|*.csv|All files (*.*)|*.*" ' Shows only .csv files
OpenFile.Title = "Browse to file:" ' Title at the top of the dialog box
If OpenFile.ShowDialog() = DialogResult.OK Then ' Makes the open file dialog box show up
strFullPath = OpenFile.FileName ' Assigns variable
strFileName = Path.GetFileName(strFullPath)
If OpenFile.FileNames.Length > 0 Then ' Checks to see if they've picked a file
tbFile.Text = strFullPath ' Puts the filename in the textbox
' The connection string for reading into data connection form
Dim connStr As String
connStr = "Driver={Microsoft Text Driver (*.txt; *.csv)}; Dbq=" + Path.GetDirectoryName(strFullPath) + "; Extensions=csv,txt "
' Sets up the data set and gets stuff from .csv file
Dim Conn As New OdbcConnection(connStr)
Dim ds As DataSet
Dim DataAdapter As New OdbcDataAdapter("SELECT * FROM [" + strFileName + "]", Conn)
ds = New DataSet
Try
DataAdapter.Fill(ds, strFileName) ' Fills data grid..
DataGridView1.DataSource = ds.Tables(strFileName) ' ..according to data source
' Catch and display database errors
Catch ex As OdbcException
Dim odbcError As OdbcError
For Each odbcError In ex.Errors
MessageBox.Show(ex.Message)
Next
End Try
' Cleanup
OpenFile.Dispose()
Conn.Dispose()
DataAdapter.Dispose()
ds.Dispose()
End If
End If
End Sub
Private Sub Button3_Click(sender As System.Object, e As System.EventArgs) Handles Button3.Click
Dim cnn As SqlConnection
Dim connectionString As String
Dim sql As String
connectionString = "data source=Excel-PCSQLEXPRESS;" &
"initial catalog=NORTHWND;Trusted_Connection=True"
cnn = New SqlConnection(connectionString)
cnn.Open()
sql = "SELECT * FROM Orders"
Dim dscmd As New SqlDataAdapter(sql, cnn)
Dim ds As New DataSet
dscmd.Fill(ds)
DataGridView1.DataSource = ds.Tables(0)
cnn.Close()
End Sub
Private Sub Button4_Click(sender As System.Object, e As System.EventArgs) Handles Button4.Click
Dim tblReadCSV As New DataTable()
tblReadCSV.Columns.Add("FName")
tblReadCSV.Columns.Add("LName")
tblReadCSV.Columns.Add("Department")
Dim csvParser As New TextFieldParser("C:UsersExcelDesktopEmployee.txt")
csvParser.Delimiters = New String() {","}
csvParser.TrimWhiteSpace = True
csvParser.ReadLine()
While Not (csvParser.EndOfData = True)
tblReadCSV.Rows.Add(csvParser.ReadFields())
End While
Dim con As New SqlConnection("Server=Excel-PCSQLEXPRESS;Database=Northwind;Trusted_Connection=True;")
Dim strSql As String = "Insert into Employee(FName,LName,Department) values(@Fname,@Lname,@Department)"
'Dim con As New SqlConnection(strCon)
Dim cmd As New SqlCommand()
cmd.CommandType = CommandType.Text
cmd.CommandText = strSql
cmd.Connection = con
cmd.Parameters.Add("@Fname", SqlDbType.VarChar, 50, "FName")
cmd.Parameters.Add("@Lname", SqlDbType.VarChar, 50, "LName")
cmd.Parameters.Add("@Department", SqlDbType.VarChar, 50, "Department")
Dim dAdapter As New SqlDataAdapter()
dAdapter.InsertCommand = cmd
Dim result As Integer = dAdapter.Update(tblReadCSV)
End Sub
End Class
以上是关于将文本文件导入DataGrid,然后保存到数据库的主要内容,如果未能解决你的问题,请参考以下文章