【问题标题】:Not able to write to excel using openpyxl in python无法在 python 中使用 openpyxl 写入 excel
【发布时间】:2021-07-17 07:36:56
【问题描述】:

谁能提供下面的 Python 中的 java 代码

public static void testActualResultsStoring(String sheetname, int rownumber, String ActualResults) 
{

   try {

      InputStream inp = new FileInputStream(a);


      Workbook wb = WorkbookFactory.create(inp);

      Sheet sheet = wb.getSheet(sheetname);

      Row row = sheet.getRow(rownumber);

      int num = row.getLastCellNum();

      Cell cell = row.createCell(num++);

      cell.setCellValue(ActualResults);

      FileOutputStream fileOut = new FileOutputStream(a);

      wb.write(fileOut);

      fileOut.close();

   } catch (Exception e) {

      e.printStackTrace();

   }

提前致谢!

【问题讨论】:

  • 你自己尝试过什么吗?
  • 是但无法获得正确的解决方案。你能帮忙吗?
  • 你可以尝试使用xlsxwriter,阅读这里的文档xlsxwriter.readthedocs.io/getting_started.html
  • 为问题添加不正确的解决方案,以及有关问题的信息
  • 我投票结束这个问题,因为这是一个离题的工作请求。

标签: python selenium openpyxl


【解决方案1】:

很多调整自然是从一种语言移植到另一种语言。在代码中包含注释,以尝试帮助解释。但是,代码应该运行,假设您有一个名为“test.xlsx”的文件和一个名为“Sheet1”的工作表。

from openpyxl import Workbook
from openpyxl import load_workbook
#Import libraries

def testActualResultsStoring(sheetname, rownumber, ActualResults):
    try:
        #Define file directory
        fileDir = 'test.xlsx'

        #wb file needs to load off of string that has file directory
        wb = load_workbook(fileDir)
        #Find sheet based on provided sheet name
        sheet = wb[sheetname]
        #No ++ in python, so we'll just find num and add 1 to it here. Note, max_column considers the entire sheet, so a more complicated answer is in order if the sheet has columns that aren't 100% filled.
        num = sheet.max_column + 1
        #No need to define a cell variable, can just assign value while calling it.
        sheet.cell(row=rownumber, column=num, value=ActualResults)

        #Save and close file
        wb.save(fileDir)
        wb.close()

    #Except case
    except(exception):
        exception.printStackTrace()

#Call on method 
testActualResultsStoring('Sheet1', 1, '1')

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-04
    • 1970-01-01
    • 2021-04-05
    • 2014-02-15
    • 1970-01-01
    • 2018-12-03
    相关资源
    最近更新 更多