使用Python在excel的新列中输入数据

时间:2017-06-23 12:07:05

标签: python excel python-3.x python-3.5 xls

我使用的是Python 3.5.2

这是我的意见:

        For i As Integer = 0 To gvDetailSecondLevel.Rows.Count - 1
        'If gvDetailSecondLevel.Rows(i).Cells(1).Text.ToString > "0" Then
        Dim jNumber As String = lblSONum.Text
        Dim lNumber As String = gvDetailSecondLevel.Rows(i).Cells(1).Text.ToString
        Dim soNumber As String = jNumber & "." & lNumber
        Using conn As New SqlConnection(myConnection2)
            conn.Open()
            Using sqlCmd As New SqlCommand
                sqlCmd.CommandText = ("Select jo.OpComplete From JobOper jo Where jo.JobNum = @JobNum")
                sqlCmd.Parameters.AddWithValue("@JobNum", soNumber)
                sqlCmd.Connection = conn
                Using sqlDa As New SqlDataAdapter(sqlCmd)
                    Using sqlDT As New DataTable()
                        sqlDa.Fill(sqlDT)
                        For Each row As DataRow In sqlDT.Rows
                            If row.Item(0) = "0" Then
                                gvDetailSecondLevel.Rows(i).BackColor = Color.Yellow
                                gvDetailSecondLevel.Rows(i).ForeColor = Color.Red
                            End If
                        Next
                    End Using
                End Using
            End Using
            conn.Close()
         End Using
         Next

运行此命令时,会创建一个excel文件并写入该文件。但是,它在一个单元格中写下所有细节。我希望excel文件看起来像这样:

{{1}}

我研究了如何在不同的列中输入数据,但我找到的所有解决方案都使用了导入xlwt,我无法安装 - 因为我没有在此PC上拥有管理员权限。

还有另一种方法吗?

1 个答案:

答案 0 :(得分:0)

我真的建议使用像openpyxl这样的东西,而不是直接处理文件。它使这个过程变得更加简单:

from openpyxl import Workbook
wb = Workbook()

# grab the active worksheet
ws = wb.active

# Data can be assigned directly to cells
ws['A1'] = 42

# Rows can also be appended
ws.append([1, 2, 3])

# Python types will automatically be converted
import datetime
ws['A2'] = datetime.datetime.now()

# Save the file
wb.save("sample.xlsx")