Archive

How to use Workbook.CheckOut in the xlwings API way

The CheckOut method of the Workbook object in Excel is used to check out a workbook from a server that is using SharePoint or a similar document management server. This functionality is essential in collaborative environments where multiple users need to work on the same file but with version control to prevent conflicts. By checking out a workbook, a user gains exclusive write access, ensuring that others cannot make changes until it is checked back in. This helps maintain data integrity and track revisions. In xlwings, this method can be accessed via the Workbook API, allowing Python scripts to programmatically manage workbook check-outs as part of automated workflows, such as in data analysis pipelines that involve shared resources.

Syntax in xlwings:
The CheckOut method is called on a Workbook object. The syntax is straightforward, as it does not require additional parameters in its basic form. However, it’s important to note that the workbook must be opened from a server location (e.g., a SharePoint URL) for this method to be applicable. If called on a local workbook, it may raise an error or have no effect.

In xlwings, the method is accessed as:

workbook.api.CheckOut()

Here, workbook refers to the xlwings Workbook object, and .api is used to access the underlying Excel object model. The CheckOut method does not take any arguments. It returns None upon successful execution. If the workbook is already checked out by another user or if there are network issues, an error may occur, which should be handled with try-except blocks in Python.

Example Usage:
Consider a scenario where an analyst needs to check out an Excel workbook from a SharePoint site to perform data updates without interference. The xlwings code below demonstrates how to open the workbook from a server path and check it out. Ensure that the path points to the server location and that you have the necessary permissions.

import xlwings as xw

# Open the workbook from a SharePoint or server location
server_path = r'https://yourcompany.sharepoint.com/sites/SharedDocuments/DataWorkbook.xlsx'
try:
    # Open the workbook in Excel (visible or background)
    wb = xw.Book(server_path)

    # Check out the workbook to gain exclusive write access
    wb.api.CheckOut()

    print("Workbook checked out successfully. You can now make changes.")

    # Perform data operations: e.g., update a cell with new data
    sheet = wb.sheets['Sheet1']
    sheet.range('A1').value = 'Updated by Python script'

    # Save changes (optional, but recommended before checking in)
    wb.save()

    # Note: To release the workbook for others, use CheckIn method later
    # wb.api.CheckIn(SaveChanges=True, Comments="Updated via xlwings")

except Exception as e:
    print(f"An error occurred: {e}")
finally:
    # Close the workbook if needed, but ensure to check in first in real scenarios
    if 'wb' in locals():
        wb.close()

How to use Workbook.CanCheckOut in the xlwings API way

The CanCheckOut member of the Workbook object in Excel’s object model is a read-only property that indicates whether a workbook stored on a Microsoft SharePoint server can be checked out to the local machine. This property is particularly useful in collaborative environments where multiple users may need to edit a shared workbook. By checking this property, a developer can determine if the workbook is available for exclusive editing before attempting a check-out operation, thus preventing potential errors or conflicts.

In xlwings, you can access the CanCheckOut property through the api property of a Book object, which provides direct access to the underlying Excel object model. The syntax for using this property is straightforward. Given an xlwings Book object, you can call the property as follows:

can_checkout_status = workbook.api.CanCheckOut

Here, workbook is an xlwings Book instance representing the open workbook. The api property exposes the native Excel VBA object model, allowing you to use the CanCheckOut property directly. The property returns a Boolean value: True if the workbook can be checked out from the server, and False otherwise. This check is essential before proceeding with the CheckOut method, which would otherwise throw an error if the workbook cannot be checked out.

For example, consider a scenario where you have a workbook opened from a SharePoint location. You can use the following code to verify its check-out status:

import xlwings as xw

# Open the workbook from a SharePoint path or a local path linked to SharePoint
wb_path = r'https://your-sharepoint-site.com/path/to/workbook.xlsx'
wb = xw.Book(wb_path)

# Check if the workbook can be checked out
if wb.api.CanCheckOut:
    print("The workbook can be checked out. Proceeding with check-out...")
    wb.api.CheckOut(wb_path) # Check out the workbook to the local machine
else:
    print("The workbook cannot be checked out at this time. It may already be checked out by another user or not stored on a server.")

In this example, the code first opens the workbook using xlwings. It then uses wb.api.CanCheckOut to determine if a check-out is possible. If it returns True, the code proceeds to call the CheckOut method, passing the workbook path as an argument to perform the check-out. If it returns False, a message is printed, indicating the workbook is unavailable for check-out, which helps avoid runtime errors.

Another practical use case is in automated scripts that manage document workflows. For instance, before performing any edits, you might want to ensure the workbook is checked out to prevent overwriting conflicts:

import xlwings as xw

# Assume the workbook is already open or referenced
wb = xw.books.active # Get the active workbook

# Verify check-out capability
if wb.api.CanCheckOut:
    try:
        wb.api.CheckOut(wb.fullname) # Attempt to check out using the workbook's full path
        print(f"Workbook '{wb.name}' has been successfully checked out.")
        # Perform edits here
        # wb.sheets[0].range('A1').value = 'Updated Data'
    except Exception as e:
        print(f"An error occurred during check-out: {e}")
else:
    print(f"Workbook '{wb.name}' is not available for check-out. Please check server status or user permissions.")

How to use Workbook.Add in the xlwings API way

The Add member of the Workbook object in the Excel object model is a method used to create a new workbook. In xlwings, which provides a powerful API to interact with Excel from Python, this functionality is accessed through the App class rather than directly from a Workbook instance. The App represents the Excel application itself, and its add() method creates a new workbook, returning a Book object (xlwings’ equivalent to a Workbook). This is essential for automating the generation of reports, dashboards, or any task requiring dynamic workbook creation.

Functionality:
The primary function is to launch a new, blank workbook in Excel. This new workbook becomes the active workbook and is added to the App.books collection. It provides a foundation for subsequent operations like adding data, creating charts, or applying formatting without needing a pre-existing file.

Syntax and Parameters:
In xlwings, the method is called on an App instance. The basic syntax is:

new_workbook = xw.App().add()

However, it is more common to use an existing application context. When you have an App object (e.g., app = xw.App() or when using xw.Book which creates an app implicitly), you call:

new_workbook = app.add()

The add() method does not take any parameters in xlwings. Its behavior is straightforward: it creates one new, empty workbook. This differs slightly from the native Excel VBA object model, where the Add method can accept a template parameter. In xlwings, to create a workbook from a template, you would typically use the Book constructor with a file path.

Code Examples:
Here are practical examples demonstrating the add() method.

  1. Creating a new workbook in a new Excel instance:
import xlwings as xw

# Start a new Excel application
app = xw.App()
# Add a new, blank workbook
new_book = app.add()
# Write data to the first cell of the active sheet
new_book.sheets[0].range('A1').value = "New Workbook Data"
# Save the workbook
new_book.save(r'C:\Reports\Report1.xlsx')
# Close the workbook and quit Excel
new_book.close()
app.quit()
  1. Adding multiple workbooks to an existing application instance:
import xlwings as xw

# Connect to a running instance or start a new one
app = xw.App(visible=True)
# Create the first new workbook
book1 = app.add()
book1.sheets[0].range('A1').value = "Workbook 1"
# Create a second new workbook
book2 = app.add()
book2.sheets[0].range('A1').value = "Workbook 2"
# At this point, two new workbooks are open in the same Excel application.
# ... perform other tasks ...
for book in app.books:
book.close()
app.quit()
  1. Using within a context manager (recommended for resource management):
import xlwings as xw

with xw.App() as app:
# The `add()` method works the same within the context
new_book = app.add()
new_book.sheets[0].range('A1').value = "Created in Context"
new_book.save('context_workbook.xlsx')
# The context manager automatically closes the book and quits the app on exit.

How to use Workbooks.Parent in the xlwings API way

The Parent property of the Workbooks object in Excel’s object model is a read-only property that returns the parent object for the specified collection. In the context of the Workbooks collection, the parent is the Excel Application object itself. This property is useful when you need to access application-level settings, methods, or properties from a workbook context, such as adjusting application settings or retrieving the application version. In xlwings, this property is accessible through the api property, which provides direct access to the underlying Excel object model, allowing for precise control and integration with Excel’s native features.

Functionality:
The primary function of the Parent property is to provide a reference to the Excel Application object that contains the Workbooks collection. This enables developers to perform operations at the application level, such as:

  • Changing global Excel settings (e.g., ScreenUpdating, Calculation).
  • Accessing other application-level collections like AddIns.
  • Retrieving application information (e.g., Version, UserName).

Syntax:
In xlwings, the syntax to access the Parent property of the Workbooks object is as follows:

app = xw.books.api.Parent
  • app: This variable will hold a reference to the Excel Application object.
  • xw.books: This refers to the Workbooks collection in xlwings.
  • .api: This provides the underlying COM object, exposing the native Excel object model.
  • .Parent: This is the property being called, returning the parent Application object.

No parameters are required for this property as it is read-only and does not accept arguments.

Code Examples:
Below are practical examples demonstrating the use of the Parent property in xlwings:

  1. Accessing Application Properties:
    This example shows how to retrieve the Excel application’s version and user name using the Parent property.
import xlwings as xw

# Connect to the active Excel instance
app = xw.apps.active

# Get the Workbooks collection's parent (Application)
excel_app = xw.books.api.Parent

# Access application-level properties
version = excel_app.Version
user_name = excel_app.UserName

print(f"Excel Version: {version}")
print(f"Current User: {user_name}")
  1. Modifying Application Settings:
    This example illustrates how to toggle the ScreenUpdating property to improve performance during macro execution.
import xlwings as xw

# Start or connect to Excel
app = xw.App(visible=True)

# Access the parent Application from Workbooks
excel_app = xw.books.api.Parent

# Disable screen updating for faster execution
excel_app.ScreenUpdating = False

# Perform data operations (e.g., adding a new workbook)
wb = xw.books.add()
wb.sheets[0].range("A1").value = "Data loaded..."

# Re-enable screen updating
excel_app.ScreenUpdating = True

# Save and close
wb.save("output.xlsx")
wb.close()
app.quit()
  1. Iterating Through Open Workbooks:
    This example uses the Parent property to list all open workbooks by accessing the Workbooks collection from the Application object.
import xlwings as xw

# Ensure Excel is running
if not xw.apps:
    xw.App(visible=True)

# Get the Application object via Parent
excel_app = xw.books.api.Parent

# Loop through all workbooks in the application
for wb in excel_app.Workbooks:
    print(f"Workbook Name: {wb.Name}")

# This provides a direct way to manage workbooks at the application level.

How to use Workbooks.Item in the xlwings API way

The Item member of the Workbooks object in Excel’s object model is a property used to access a specific workbook within the Workbooks collection. In xlwings, this functionality is typically accessed through the books property of the App object, which represents the collection of open workbooks. The Item property allows you to retrieve a workbook by its index number (position in the collection) or by its name (as a string). This is essential for programmatically manipulating specific workbooks when multiple workbooks are open, enabling you to set a workbook as the active object, read data, or perform other operations.

Syntax in xlwings:
While xlwings does not explicitly expose an Item method, the books collection behaves similarly. You can access a workbook using indexing or key-based lookup.

  • By index (1-based, like Excel VBA): app.books[index]
  • By name (workbook filename): app.books[name]

Parameters:

  • index: An integer representing the position of the workbook in the books collection. The index starts at 1 for the first workbook opened or referenced.
  • name: A string that matches the full name (including extension) of the workbook, such as “Data.xlsx”. If the workbook is saved, you can use the base name without the path if it’s unique among open workbooks.

Examples:

  1. Access by Index:
    Suppose you have two workbooks open: “Report.xlsx” (opened first) and “Analysis.xlsx” (opened second). To reference the first workbook:
import xlwings as xw
app = xw.apps.active # Get the active Excel application
first_workbook = app.books[0] # Index 0 in xlwings corresponds to VBA's Item(1)
print(first_workbook.name) # Output: Report.xlsx

Note: xlwings uses 0-based indexing for collections in Python, unlike VBA’s 1-based Item. So app.books[0] is equivalent to Workbooks.Item(1) in VBA.

  1. Access by Name:
    To directly access a workbook named “Financials.xlsx”:
import xlwings as xw
app = xw.apps.active
target_workbook = app.books['Financials.xlsx']
target_workbook.activate() # Make it the active workbook

If multiple workbooks have similar names, ensure you use the full filename. This method is case-insensitive on Windows but case-sensitive on macOS.

  1. Iterating Through Workbooks:
    You can loop through all open workbooks using the books collection, which internally utilizes the Item property:
import xlwings as xw
app = xw.apps.active
for wb in app.books:
    print(f"Workbook: {wb.name}, Sheets: {[sheet.name for sheet in wb.sheets]}")

This iterates over each workbook and prints its name along with sheet names, demonstrating how Item underpins collection access.

  1. Error Handling:
    When accessing by name, if the workbook isn’t open, xlwings raises a KeyError. You can handle this gracefully:
import xlwings as xw
app = xw.apps.active
try:
    wb = app.books['NonExistent.xlsx']
except KeyError:
    print("Workbook not found. Please check if it's open.")

How to use Workbooks.Creator in the xlwings API way

The Creator property of the Workbooks object in Excel’s object model is a read-only property that returns a Long value representing the creator code for the application that created the file. This is particularly useful for identifying the original application when dealing with files that may have been created in different versions of Excel or other spreadsheet programs. In xlwings, this property can be accessed through the api property, which provides direct access to the underlying Excel object model.

Functionality:
The Creator property helps in determining the application that originally created the workbook. It returns a four-character code (as a Long integer) that corresponds to the creator. For example, Microsoft Excel typically uses the code “XCEL”. This can be useful in scenarios where you need to verify file origins or handle compatibility issues.

Syntax:
In xlwings, the syntax to access the Creator property is:

workbook.api.Creator

Here, workbook refers to an xlwings Book object. The property does not take any parameters and returns a Long value.

Example:
Below is a practical example of how to use the Creator property in xlwings to check the creator of an open workbook. This code opens a workbook, retrieves the creator code, and prints it along with a descriptive message.

import xlwings as xw

# Open an existing workbook or connect to an open one
wb = xw.Book('example.xlsx') # Replace with your file path

# Access the Creator property via the api
creator_code = wb.api.Creator

# Convert the Long code to a readable string (optional)
# Typically, you might map known codes to application names
if creator_code == 1480803660: # This is 'XCEL' in decimal for Excel
    creator_name = "Microsoft Excel"
else:
    creator_name = "Unknown Application"

# Output the result
print(f"The workbook creator code is: {creator_code}")
print(f"This corresponds to: {creator_name}")

# Close the workbook if needed (optional)
wb.close()

How to use Workbooks.Count in the xlwings API way

The Workbooks.Count property in xlwings is a direct mapping from the Excel Object Model’s Workbook.Count property under the Workbooks collection. It provides a simple yet powerful way to programmatically determine the number of currently open workbooks in an Excel instance. This is particularly useful in automation scripts where you need to check the state of the Excel application, iterate through all open workbooks, or ensure a specific number of workbooks are present before performing batch operations.

Functionality:
The primary function of Workbooks.Count is to return a Long integer representing the count of all open workbook files in Microsoft Excel. This includes workbooks that are visible, hidden, or add-ins. It is a read-only property, meaning you can retrieve its value but cannot set it directly to change the number of open workbooks.

Syntax and Parameters:
In xlwings, you access this property through the app object, which represents the Excel application. The syntax is straightforward:

count = app.books.count
  • app: This is the xlwings App instance, representing the Excel application. You typically obtain it using xw.apps (to get a running instance) or xw.App() (to create a new one).
  • books: This is the xlwings equivalent of the Excel Workbooks collection. It provides access to all open workbooks.
  • count: This is the property that returns the integer count. No parameters are required.

There are no parameters to specify, as count is a simple property. Its value is dynamically determined by the state of the Excel application at the moment of access.

Code Examples:

  1. Basic Retrieval of Count:
    This example connects to the active Excel instance and prints the number of open workbooks.
import xlwings as xw

# Connect to the active Excel instance
app = xw.apps.active
# Get the count of open workbooks
open_count = app.books.count
print(f"Number of open workbooks: {open_count}")
  1. Conditional Logic Based on Count:
    This script checks if there are any workbooks open. If none are open, it creates a new one; otherwise, it activates the first workbook.
import xlwings as xw

app = xw.apps.active
if app.books.count == 0:
    print("No workbooks open. Creating a new one.")
    new_wb = app.books.add()
else:
    print(f"{app.books.count} workbook(s) open.")
    first_wb = app.books[0] # Access the first workbook in the collection
    first_wb.activate()
  1. Iterating Through All Open Workbooks:
    This example uses the count to loop through each open workbook and print its name. Using app.books.count in the range() function ensures you iterate over the exact number of items.
import xlwings as xw

app = xw.apps.active
num_books = app.books.count
print(f"Iterating through {num_books} workbook(s):")
for i in range(num_books):
    wb = app.books[i]
    print(f" - Workbook {i+1}: {wb.name}")
  1. Monitoring Workbook State:
    In a more dynamic scenario, you might use the count in a loop to wait for a specific number of workbooks to be opened by a user.
import xlwings as xw
import time

app = xw.apps.active
print("Waiting for at least 2 workbooks to be open...")
while app.books.count < 2:
time.sleep(0.5) # Check every half second
print("Condition met! Proceeding with automation.")
# ... perform tasks requiring multiple workbooks

How to use Workbooks.Application in the xlwings API way

The Application member of the Workbooks object in the Excel object model represents the Excel application itself. In xlwings, this is typically accessed through the app property when you have a workbook or a specific object, but you can also directly reference the Excel application instance. The Application object provides a wide range of properties and methods to control the Excel environment, such as settings for calculation, screen updating, and accessing other top-level objects.

Functionality:
The Application member allows you to interact with the Excel application globally. Common uses include:

  • Controlling Excel settings (e.g., turning off screen updates for performance).
  • Accessing properties like the version of Excel or the user name.
  • Managing workbooks and windows at the application level.
  • Executing application-wide methods, such as calculating all open workbooks.

Syntax:
In xlwings, you typically start by connecting to an existing Excel instance or creating a new one. The Application is represented by the app object. For example:

import xlwings as xw

# Connect to an existing Excel instance or start a new one
app = xw.App(visible=True, add_book=False)

Once you have the app object, you can access its properties and methods. The general syntax for accessing the Application member via xlwings is:

  • app.property_name for properties (e.g., app.version to get the Excel version).
  • app.method_name(parameters) for methods (e.g., app.calculate() to recalculate all open workbooks).

Key parameters for methods often include optional arguments that control behavior. For example, in methods that involve calculations, you might specify the calculation type. Here’s a table for common Application properties and methods in xlwings:

Member Typexlwings API ExampleDescriptionParameters/Values
Propertyapp.versionReturns the Excel version as a string.None
Propertyapp.screen_updatingGets or sets whether screen updating is enabled (Boolean).Set to True or False to toggle.
Methodapp.calculate()Forces a recalculation of all open workbooks.No parameters required.
Methodapp.quit()Closes the Excel application.None, but ensure to save workbooks first.
Methodapp.activate()Activates the Excel application window.None

Examples:
Here are practical xlwings code examples using the Application member:

  1. Getting Excel Version and User Name:
import xlwings as xw

app = xw.App(visible=False) # Start Excel in the background
print(f"Excel Version: {app.version}")
print(f"User Name: {app.user_name}")
app.quit() # Close Excel
  1. Controlling Screen Updates for Performance:
import xlwings as xw

app = xw.App(visible=True)
app.screen_updating = False # Turn off screen updates
# Perform data operations (e.g., open workbooks, write data)
wb = app.books.add() # Add a new workbook
wb.sheets[0].range("A1").value = "Hello, World!"
app.screen_updating = True # Turn screen updates back on
wb.save("example.xlsx")
app.quit()
  1. Recalculating All Workbooks:
import xlwings as xw

app = xw.App(visible=True)
# Open multiple workbooks and perform calculations
wb1 = app.books.open("workbook1.xlsx")
wb2 = app.books.open("workbook2.xlsx")
# After making changes to formulas, recalculate
app.calculate() # Forces recalculation across all open workbooks
wb1.save()
wb2.save()
app.quit()
  1. Activating Excel and Managing Windows:
import xlwings as xw

app = xw.App(visible=True)
app.activate() # Brings Excel to the foreground
wb = app.books.add()
# Customize window state (e.g., maximize)
app.windows[0].window_state = 'maximized'
print(f"Number of open workbooks: {len(app.books)}")
app.quit()

How to use Workbooks.OpenXML in the xlwings API way

The OpenXML member of the Workbooks collection in Excel’s object model is a method that allows developers to open an Excel workbook from an XML file format, specifically targeting files in the Office Open XML format (such as .xlsx, .xlsm). This method is particularly useful when you need to programmatically load workbooks that are stored in this modern, XML-based format, ensuring compatibility and efficient handling of Excel 2007 and later file types. In xlwings, which provides a Pythonic interface to Excel’s COM automation, this functionality is accessed through the app.books.open() method, as xlwings abstracts the underlying COM methods like OpenXML into a more unified open function. However, understanding the original OpenXML method’s parameters helps in utilizing the xlwings equivalent effectively.

Functionality: The primary purpose is to open an Excel workbook from an Office Open XML file. It enables automation scenarios where workbooks are generated or stored as .xlsx files, and you need to manipulate them via Python scripts. This method ensures that the workbook is loaded correctly with all its components, such as worksheets, charts, and defined names, from the XML structure.

Syntax in xlwings: While xlwings does not expose a direct OpenXML method, it uses the open() method of the Books collection, which internally handles various file formats, including Open XML. The syntax is:
app.books.open(fullname)
Here, app is an instance of the xlwings App class representing an Excel application. The parameter fullname is a string specifying the full path and filename of the workbook to open (e.g., “C:\Data\report.xlsx”). This method corresponds to the VBA Workbooks.OpenXML method but simplifies it by not requiring explicit format parameters—xlwings automatically detects the file type based on the extension.

In the native Excel object model, OpenXML has additional parameters like LoadOption to control how the XML is loaded, but xlwings’ open() method abstracts these details. For advanced usage, you can pass other optional arguments supported by xlwings’ open() to mimic OpenXML behavior, such as update_links or read_only, though these are not XML-specific. For example, to open a workbook in read-only mode similar to using OpenXML with caution, you can set read_only=True.

Code Example:
Below is an xlwings API code instance that demonstrates opening an Open XML workbook using the open() method, which effectively utilizes the underlying OpenXML functionality. This example assumes Excel is running or will be launched.

import xlwings as xw

# Start or connect to an Excel application
app = xw.App(visible=True) # Set visible=False for background operation

# Open an Open XML file (.xlsx) using the books.open method
# This internally uses the OpenXML mechanism for .xlsx files
workbook_path = r"C:\Users\Example\Documents\budget.xlsx"
wb = app.books.open(workbook_path)

# Perform operations: e.g., read data from a specific cell
data = wb.sheets['Sheet1'].range('A1').value
print(f"Data from A1: {data}")

# Save any changes (if needed) and close the workbook
wb.save() # Optional: save changes
wb.close()

# Quit the Excel application
app.quit()

How to use Workbooks.OpenText in the xlwings API way

The OpenText member of the Workbooks object in the Excel object model is a method used to import and parse a text file into a new Excel workbook. This is particularly useful for automating the loading of data from delimited text files (like CSV or TSV) or fixed-width text files directly into Excel without manual intervention. In xlwings, this functionality is accessed through the api property, which provides direct access to the underlying Excel object model, allowing precise control over the import process.

Syntax in xlwings:
The xlwings API call follows the pattern: xlwings.Book.api.OpenText(...). However, since OpenText is a method of the Workbooks collection, it is typically used to create a new workbook. In xlwings, you can access it via the Excel application object. The general syntax is:

app = xw.App(visible=False) # Create an invisible Excel instance
app.api.Workbooks.OpenText(Filename, ...)

The OpenText method has numerous parameters to customize the import. Key parameters include:

  • Filename (required, String): The full path and name of the text file to import.
  • Origin: Specifies the file origin (e.g., xlWindows for Windows or xlMacintosh for Mac). Often set to xlWindows (value 437) by default.
  • StartRow (Long): The starting row for parsing (default is 1).
  • DataType (XlTextParsingType): Sets how columns are parsed. Use xlDelimited (value 1) for delimited files (like CSV) or xlFixedWidth (value 2) for fixed-width files.
  • TextQualifier (XlTextQualifier): Specifies the text qualifier character, such as xlTextQualifierDoubleQuote (value 1) for double quotes.
  • ConsecutiveDelimiter (Boolean): True to treat consecutive delimiters as one.
  • Tab, Semicolon, Comma, Space, Other, OtherChar: Boolean parameters to set delimiters. For example, set Comma=True for CSV files. If Other=True, specify the character in OtherChar.
  • FieldInfo (Array): An array of arrays specifying the data type and width for each column. For delimited files, it often uses xlGeneralFormat (value 1). Example: [[1, 1], [2, 1]] sets the first two columns to general format.

Example:
Here is an xlwings API code example that imports a comma-delimited CSV file, treating consecutive commas as one delimiter, and starting from the first row:

import xlwings as xw

# Start Excel in the background
app = xw.App(visible=False)

# Define the text file path
file_path = r'C:\Data\sales.csv'

# Open the text file using OpenText
# Parameters: Filename, StartRow=1, DataType=xlDelimited, Comma=True, ConsecutiveDelimiter=True
workbook = app.api.Workbooks.OpenText(
Filename=file_path,
Origin=437, # xlWindows
StartRow=1,
DataType=1, # xlDelimited
TextQualifier=1, # xlTextQualifierDoubleQuote
ConsecutiveDelimiter=True,
Comma=True,
FieldInfo=[[1, 1], [2, 1], [3, 1]] # Set first three columns to general format
)

# Save the workbook as an Excel file
workbook.SaveAs(r'C:\Data\sales_imported.xlsx')
workbook.Close()
app.quit()