将记录从Excel文件上传到服务器-桌面应用

时间:2019-12-07 10:37:20

标签: json sql-server excel exe desktop-application

我有以下要求:

我的PC的 D:// 驱动器中有一个名为 BATCH 的文件夹。

现在,此 D:// BATCH 包含具有任意随机名称的excel文件。每个excel文件只有一个记录。

我必须创建.exe文件或任何允许用户浏览 BATCH 文件夹的桌面应用程序,然后可以将内容或数据从excel文件上传到我们的服务器。我们必须将excel数据放入 JSON ,然后将其上传到服务器。

另一件事是,如果我从3个文件中上传了数据,然后用户再次尝试通过选择文件夹来上传,则新的或未上传的数据应仅上传那些数据。每天使用连接的计算机生成BATCH文件夹中的数据。

我的背景是Web和移动开发。因此,如上所述,在实现此目标方面有些困惑。

那么,我该如何实现呢?我必须使用哪种技术或哪些工具会有用?

感谢支持。

2 个答案:

答案 0 :(得分:1)

这个问题太广泛了,您可以通过多种方式实现您的要求。

如果您考虑使用c#,则可以开发一个WPFWinforms项目。

您将需要执行以下基本步骤

  1. 一种用于浏览和选择文件的功能,例如FolderBrowserDialog中可用的System.Windows.Forms。如果您使用的是WPF,则必须添加对库的引用
  2. 阅读excel内容。在这种情况下,您可能需要引用任何库/裸包,例如EpplusMicrosoft.Office.Interop.ExcelLinqToExcelExcelLibrary
  3. 使用Newtonsoft.Json nuget包将数据转换为json格式
  4. 将数据上传或保存到SQL Server-在这里,您需要一个到数据库的连接字符串,并将其保存在.config文件中。您可以为此使用ADO,linq到sql等。

示例代码

OpenFileDialog openFileDialog = new OpenFileDialog();
        openFileDialog.Filter = "Excel files (*.xls)|*.csv|All files (*.*)|*.*";
        if (openFileDialog.ShowDialog()== DialogResult.OK)
{
       //Open file and read contents

       var excelFile = new LinqToExcel.ExcelQueryFactory(path);


            var query =
                from row in excelFile.Worksheet("Sheet1")
                let item = new
                {
                    Column1 = row["Column1"].Cast<string>(),
                    Column2 = row["Column2"].Cast<int>(),

                }

                select item;

            foreach (var item in query)
            {
                MyCustomClass myClass = new MyCustomClass();
                myClass.Column1 = item.Column1;
                myClass.Column2 = item.Column2;

                //Do something
            }
            //convert to json
            // Save to database
}

答案 1 :(得分:1)

可能有很多方法可以给这只猫剥皮。也许将文件夹中所有Excel文件中的所有内容导入到一个Excel文件中,并将其导出到SQL Server。只是一个想法。

Sub InsertInto()

'Declare some variables
Dim cnn As adodb.Connection
Dim cmd As adodb.Command
Dim strSQL As String

'Create a new Connection object
Set cnn = New adodb.Connection

'Set the connection string
cnn.ConnectionString = "Provider=SQLOLEDB.1;Integrated Security=SSPI;Persist Security Info=True;Initial Catalog=Northwind;Data Source=Server_Name"

'Create a new Command object
Set cmd = New adodb.Command

'Open the Connection to the database
cnn.Open

'Associate the command with the connection
cmd.ActiveConnection = cnn

'Tell the Command we are giving it a bit of SQL to run, not a stored procedure
cmd.CommandType = adCmdText

'Create the SQL
strSQL = "UPDATE TBL SET JOIN_DT = '2019-12-10' WHERE EMPID = 2"

'Pass the SQL to the Command object
cmd.CommandText = strSQL


'Execute the bit of SQL to update the database
cmd.Execute

'Close the connection again
cnn.Close

'Remove the objects
Set cmd = Nothing
Set cnn = Nothing

End Sub

只需稍微修饰一下我的原始答案即可...您可以使用以下概念轻松地将文件夹中多个Excel文件中的数据导入到一个Excel文件中。

Sub Basic_Example_1()
    Dim MyPath As String, FilesInPath As String
    Dim MyFiles() As String
    Dim SourceRcount As Long, Fnum As Long
    Dim mybook As Workbook, BaseWks As Worksheet
    Dim sourceRange As Range, destrange As Range
    Dim rnum As Long, CalcMode As Long

    'Fill in the path\folder where the files are
    MyPath = "C:\Users\Ron\test"

    'Add a slash at the end if the user forget it
    If Right(MyPath, 1) <> "\" Then
        MyPath = MyPath & "\"
    End If

    'If there are no Excel files in the folder exit the sub
    FilesInPath = Dir(MyPath & "*.xl*")
    If FilesInPath = "" Then
        MsgBox "No files found"
        Exit Sub
    End If

    'Fill the array(myFiles)with the list of Excel files in the folder
    Fnum = 0
    Do While FilesInPath <> ""
        Fnum = Fnum + 1
        ReDim Preserve MyFiles(1 To Fnum)
        MyFiles(Fnum) = FilesInPath
        FilesInPath = Dir()
    Loop

    'Change ScreenUpdating, Calculation and EnableEvents
    With Application
        CalcMode = .Calculation
        .Calculation = xlCalculationManual
        .ScreenUpdating = False
        .EnableEvents = False
    End With

    'Add a new workbook with one sheet
    Set BaseWks = Workbooks.Add(xlWBATWorksheet).Worksheets(1)
    rnum = 1

    'Loop through all files in the array(myFiles)
    If Fnum > 0 Then
        For Fnum = LBound(MyFiles) To UBound(MyFiles)
            Set mybook = Nothing
            On Error Resume Next
            Set mybook = Workbooks.Open(MyPath & MyFiles(Fnum))
            On Error GoTo 0

            If Not mybook Is Nothing Then

                On Error Resume Next

                With mybook.Worksheets(1)
                    Set sourceRange = .Range("A1:C1")
                End With

                If Err.Number > 0 Then
                    Err.Clear
                    Set sourceRange = Nothing
                Else
                    'if SourceRange use all columns then skip this file
                    If sourceRange.Columns.Count >= BaseWks.Columns.Count Then
                        Set sourceRange = Nothing
                    End If
                End If
                On Error GoTo 0

                If Not sourceRange Is Nothing Then

                    SourceRcount = sourceRange.Rows.Count

                    If rnum + SourceRcount >= BaseWks.Rows.Count Then
                        MsgBox "Sorry there are not enough rows in the sheet"
                        BaseWks.Columns.AutoFit
                        mybook.Close savechanges:=False
                        GoTo ExitTheSub
                    Else

                        'Copy the file name in column A
                        With sourceRange
                            BaseWks.cells(rnum, "A"). _
                                    Resize(.Rows.Count).Value = MyFiles(Fnum)
                        End With

                        'Set the destrange
                        Set destrange = BaseWks.Range("B" & rnum)

                        'we copy the values from the sourceRange to the destrange
                        With sourceRange
                            Set destrange = destrange. _
                                            Resize(.Rows.Count, .Columns.Count)
                        End With
                        destrange.Value = sourceRange.Value

                        rnum = rnum + SourceRcount
                    End If
                End If
                mybook.Close savechanges:=False
            End If

        Next Fnum
        BaseWks.Columns.AutoFit
    End If

ExitTheSub:
    'Restore ScreenUpdating, Calculation and EnableEvents
    With Application
        .ScreenUpdating = True
        .EnableEvents = True
        .Calculation = CalcMode
    End With
End Sub

有关如何从多个Excel文件/源获取数据,将其合并为一个文件/源的信息,请参见下面的链接。

http://www.rondebruin.nl/win/s3/win008.htm

对此类内容保持开放的态度。还有其他几种方法可以完成基本上相同的事情。