0

I found out how to change text in Excel file with Aspose.Cells for Python through Java:

import jpype
import asposecells
jpype.startJVM()
from asposecells.api import *

import os
os.chdir(r"c:\Users\Manager\Desktop")
os.getcwd()
workbook = Workbook('Invoice.xlsx')

# Create replace options
replace = ReplaceOptions()


# Set case sensitivity and text matching options
replace.setCaseSensitive(False)
replace.setMatchEntireCellContents(False)



# Replace text
workbook.replace("one","two", replace)
workbook.replace("one","five", replace)




workbook.save("Invoice 2.xlsx");

But I need to replace "one" in first row to "two", "one" in tenth row to "five". As you see, first replacement affects on all file. How can I fix it?

3
  • Can you give an example, as to how "Invoice.xlsx" looks like? Commented May 15 at 8:37
  • If you know the range where you want to make the replacement, you should be able to use FindOptions setRange: reference.aspose.com/cells/java/com.aspose.cells/findoptions and here's example with Python for .NET with exact thing you are doing: docs.aspose.com/cells/python-net/… Commented May 15 at 8:42
  • Modify this worksheet using Python 3.13.3.Replace workbook.replace("one","five", replace) to workbook.replace("two","five", replace) Commented May 15 at 9:53

2 Answers 2

0

You can try something like this:

worksheet = workbook.getWorksheets().get(0)
worksheet.getCells().replace("one", "two", ReplaceOptions(), CellArea(0, 0, 0, 100))  # Row 1 
worksheet.getCells().replace("one", "five", ReplaceOptions(), CellArea(9, 0, 9, 100))  # Row 10
Sign up to request clarification or add additional context in comments.

Comments

0

You can access rows separately and apply a replace only to each row, respectively:

workbook = Workbook('test.xlsx')

def replace_in_row(worksheet, row, old_value, new_value):
    for cell in worksheet.getCells().getRows().get(row):
        if old_value in str(cell.getValue()):
            cell.setValue(str(cell.getValue()).replace(old_value, new_value))

worksheet = workbook.getWorksheets().get(0)
replace_in_row(worksheet, 0, "one", "two")
replace_in_row(worksheet, 9, "one", "five")

or alternatively - adding to @MahrezBenHamad's answer - determine the column range and

max_column = worksheet.getCells().getMaxColumn()

worksheet.getCells().replace("one", "two", ReplaceOptions(), CellArea(0, 0, 0, max_column))
worksheet.getCells().replace("one", "five", ReplaceOptions(), CellArea(9, 0, 9, max_column))

1 Comment

I tried your first variant and it works well.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.