Я хочу импортировать текстовый файл в Datagrid, и когда я нажму «Сохранить», он сохранит таблицу в базе данных. введите описание изображения здесь

Я пробовал этот код. Но там написано «Не удалось найти столбец 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('\t');
                        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.");
        }
  }

Это текстовый файл: я хочу, чтобы AttendanceCode "1010" был только один столбец введите описание изображения здесь Как мне исправить ошибку? а что поставить в кнопку Сохранить?

0
Jhona 3 Мар 2018 в 07:25

3 ответа

Лучший ответ

Я понял это сам, это ответ:

string[] parts = line.Split('\t');
                        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);
0
Jhona 6 Мар 2018 в 05:23

Проблема в том, что ваша таблица данных имеет три столбца, а текстовый файл - шесть, поэтому, когда ваш код

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('\t');
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));
0
Hambone 5 Мар 2018 в 12:12

Код ниже должен охватывать все для вас.

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:\Users\Excel\Desktop\OrdersTest.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-PC\SQLEXPRESS;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-PC\SQLEXPRESS;" &
        "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:\Users\Excel\Desktop\Employee.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-PC\SQLEXPRESS;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
-3
ASH 3 Мар 2018 в 05:44