Visual Basic - 将文本框保存到Excel文件

时间:2018-04-02 18:45:14

标签: excel vb.net filestream

我想设置一个网页,用户可以将工作单粘贴到文本框中,单击“提交”,然后将其写入服务器上的.xlsx。

我已经将StreamWriter保存为.txt,但无效/与.xlsx不兼容。

有人能指出我正确的方向吗?我不是在寻找有人为我做这件事,但我不熟悉编码,所以我有很多愚蠢的问题。

1 个答案:

答案 0 :(得分:0)

如果您让用户将工作订单输入到数据网格而不是文本框中,那么导出到excel会更容易,看起来更好。

    Function EXPTOEXLS()

    Dim rowsTotal, colsTotal As Short
    Dim I, j, iC As Short
    System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.WaitCursor
    Dim xlApp As New Excel.Application 'need to add reference to "Microsoft Excel xx object library" then add  |  IMPORTS microsoft.office.interop  (add to top)

    Try
        Dim excelBook As Excel.Workbook = xlApp.Workbooks.Add
        Dim excelWorksheet As Excel.Worksheet = CType(excelBook.Worksheets(1), Excel.Worksheet)
        xlApp.Visible = True
        rowsTotal = DataGridView1.RowCount - 1
        colsTotal = DataGridView1.Columns.Count - 1

        With excelWorksheet
            .Cells.Select()
            .Cells.Delete()
            For iC = 0 To colsTotal
                .Cells(1, iC + 1).Value = DataGridView1.Columns(iC).HeaderText
            Next

            For I = 0 To rowsTotal
                For j = 0 To colsTotal
                    .Cells(I + 2, j + 1).value = DataGridView1.Rows(I).Cells(j).Value
                Next j
            Next I

            .Rows("1:1").Font.FontStyle = "Bold"
            .Rows("1:1").Font.Size = 10
            .Cells.Columns.AutoFit()
            .Cells.Select()
            .Cells.EntireColumn.AutoFit()
            .Cells(1, 1).Select()
        End With

    Catch ex As Exception
        MsgBox(ex.Message)
    Finally
        'RELEASE ALLOACTED RESOURCES
        System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.Default
        xlApp = Nothing
    End Try
End Function