Tutorial on How to Add and Manage Excel VBA Macros in C#

VBA macros provide a convenient way to automate data processing, formatting, and business logic within Excel, especially for repetitive or rule-based tasks. However, managing macros manually inside Excel becomes inefficient when you need to generate, update, or maintain files at scale.

For .NET developers, a more scalable approach is to programmatically add macros to Excel using C#. By working with Excel VBA in C#, you can write Excel macros, read existing macro code, and modify VBA logic across multiple files without opening Excel and manually editing the VBA code.

In this article, you'll learn how to add, read, and edit Excel VBA macros in C# for automated workflows. Using Spire.XLS for .NET, you can directly manipulate VBA projects embedded in Excel files without requiring Microsoft Excel installation.

Quick Navigation


Understanding Excel Macros and How C# Works with Them

An Excel macro is essentially VBA (Visual Basic for Applications) code stored inside a workbook. In macro-enabled files (such as .xlsm), this code is organized within a VBA project, which contains modules and procedures.

In practice, most programmatic macro operations focus on standard modules, which are simple containers for VBA procedures (Sub or Function). When working with C#, you typically do not interact with Excel UI elements like buttons or events. Instead, you directly create modules and inject VBA code.

From a technical perspective, macros are not just executable scripts—they are part of the file structure. This means they can be accessed and modified programmatically, provided that your tool supports VBA project manipulation.

In C#, there are two main approaches to working with Excel macros:

  • Using Microsoft Excel Interop to automate Excel
  • Using standalone libraries such as Spire.XLS for .NET to manipulate the file directly

The first approach depends on Excel being installed and is typically used to execute macros. The second approach allows you to create, read, edit, and delete VBA code directly inside Excel files, making it more suitable for backend services and automated workflows.

In the following sections, we'll focus on the second approach and demonstrate how to manage Excel macros entirely in C#.


Environment Setup: Install Spire.XLS for .NET

Before working with Excel macros in C#, you need to install Spire.XLS for .NET, which allows you to manage Excel files and manipulate VBA projects without requiring Microsoft Excel.

Install via NuGet

You can install Spire.XLS for .NET using NuGet Package Manager:

Install-Package Spire.XLS

Or via the .NET CLI:

dotnet add package Spire.XLS

You can also download the Spire.XLS for .NET package and add it to your project manually.

Project Requirements

  • .NET Framework, .NET Core, .NET Standard, or .NET 5+
  • No Microsoft Excel installation required
  • Supports Windows, Linux, and macOS environments

The library is runtime-agnostic and can be used in any .NET-supported environment, including web, desktop, and cross-platform applications.

Namespace to Import

After installation, include the following namespaces in your project:

using Spire.Xls;

Once the setup is complete, you can start creating, reading, and modifying Excel VBA macros programmatically.


How to Add a Macro to Excel in C# (Complete Example)

Before writing macro code, it's important to understand how Spire.XLS exposes the VBA structure in Excel:

  • Workbook.VbaProject represents the VBA project embedded in the workbook
  • IVbaProject.Modules provides access to all VBA modules
  • IVbaModule represents an individual module that stores macro code

In addition to modules, the VBA project also supports project-level configuration, such as name, description, password protection, and conditional compilation settings.

The following example shows how to create a VBA project, configure its properties, add a module, and write a macro into an Excel file programmatically.

using Spire.Xls;

Workbook workbook = new Workbook();

// Create VBA project
IVbaProject vbaProject = workbook.VbaProject;

// Configure project-level properties (optional but important in real scenarios)
vbaProject.Name = "ReportGenerator";
vbaProject.Description = "VBA project for generating quarterly reports";
vbaProject.Password = "securepassword";
vbaProject.LockProjectView = false;
vbaProject.HelpFileName = "ReportGeneratorHelp.chm";
vbaProject.ConditionalCompilation = "DEBUG_MODE=1"; // External compile-time flag

// Add a VBA module
IVbaModule vbaModule = vbaProject.Modules.Add("ReportModule", VbaModuleType.Module);

// Write VBA macro code
vbaModule.SourceCode = @"
Sub GenerateQuarterlyReport()
    Dim ws As Worksheet
    Dim i As Integer
    Dim quarter As String

    Set ws = ActiveSheet
    ws.Cells.Clear

    ' Prompt user input
    quarter = InputBox(""Enter quarter (e.g., Q1 2026):"", ""Report Generation"")

    With ws
        .Range(""A1:E1"").Value = Array(""Date"", ""Product"", ""Region"", ""Sales"", ""Status"")

        For i = 1 To 50
            .Cells(i + 1, 1).Value = DateSerial(2026, 1 + Int((i - 1) / 17), 1 + ((i - 1) Mod 17))
            .Cells(i + 1, 2).Value = ""Product "" & (1 + Int((i - 1) / 10))
            .Cells(i + 1, 3).Value = Choose((i Mod 5) + 1, ""North"", ""South"", ""East"", ""West"", ""Central"")
            .Cells(i + 1, 4).Value = Round(Rnd() * 10000, 2)
            .Cells(i + 1, 5).Value = IIf(.Cells(i + 1, 4).Value > 5000, ""Target Met"", ""Below Target"")
        Next i

        .Columns(""A:E"").AutoFit

        ' Conditional compilation example
        #If DEBUG_MODE = 1 Then
            MsgBox ""DEBUG: Report generated (50 rows)"", vbInformation, ""Debug Info""
        #End If
    End With

    MsgBox ""Quarterly report for "" & quarter & "" generated successfully!"", vbInformation, ""Report Status""
End Sub";

// Save as macro-enabled Excel file
workbook.SaveToFile("QuarterlyReportGenerator.xlsm", FileFormat.Version2016);
workbook.Dispose();

Below is a preview of the generated Macro in Excel:

Add Macros to Excel Using C#

In this workflow, Spire.XLS allows you to construct the full VBA structure—not only modules and macro code, but also project-level metadata and compilation behavior—directly in code. This is conceptually similar to configuring a VBA project in the editor, but fully automated and independent of Excel.

Key API Breakdown

  • workbook.VbaProject

    Initializes or retrieves the VBA project within the workbook.

  • vbaProject.Modules.Add(name, type)

    Adds a new module to the project as a container for macro code.

  • vbaModule.SourceCode

    Defines the full VBA script inside the module.

  • vbaProject.Description

    Adds a description to the VBA project.

  • vbaProject.CodePage

    Defines the character encoding used in the VBA project.

  • vbaProject.Password / LockProjectView

    Controls access and visibility of the VBA project.

  • vbaProject.ConditionalCompilation

    Enables compile-time flags (e.g., debug logic) inside VBA using #If.

Workbooks containing macros must be saved in macro-enabled formats such as .xls, .xlsm, .xltm, or .xlsb, as other formats (e.g., .xlsx) do not support VBA. Refer to the FileFormat enumeration to correctly set the output format when saving.


Reading, Editing, and Removing Excel Macros in C#

Once a VBA project exists, you can use Spire.XLS to inspect and modify its contents programmatically, including both module code and project-level metadata.

In real-world scenarios, this allows you to analyze existing macros, update business logic, enforce security settings, or remove legacy VBA code without opening Excel. Whether you're maintaining automated reporting systems or processing third-party Excel files, having full control over VBA projects in code is essential.

Read Macro Code and Project-Level Metadata

To read macros from an Excel file, load the workbook and iterate through all modules in the VBA project.

using Spire.Xls;

Workbook workbook = new Workbook();
workbook.LoadFromFile("QuarterlyReportGenerator.xlsm");

IVbaProject vbaProject = workbook.VbaProject;

string macroInfo = "VBA Project Name: " + vbaProject.Name + Environment.NewLine;
macroInfo += "Code Page: " + vbaProject.CodePage + Environment.NewLine;
macroInfo += "Is Protected: " + vbaProject.IsProtected + Environment.NewLine;

foreach (IVbaModule module in vbaProject.Modules)
{
    macroInfo += Environment.NewLine + "Module: " + module.Name + Environment.NewLine;
    macroInfo += "Source Code:" + Environment.NewLine;
    macroInfo += module.SourceCode + Environment.NewLine;
}

Console.WriteLine(macroInfo);

System.IO.File.WriteAllText("MacroAnalysis.txt", macroInfo);
workbook.Dispose();

Below is a preview of the console output:

Read Macros from Excel Using C#

Here, each module exposes its VBA code through the SourceCode property, while the VBA project itself provides metadata such as name, encoding, and protection status.

The property vbaProject.IsProtected in this example indicates whether the VBA project is protected (locked for viewing or editing).

Edit Macro Code and Project-Level Metadata

To edit a macro, access a specific module and update its SourceCode. You can also modify project-level properties if needed. If the VBA project is protected, the correct password must be provided through vbaProject.Password before making such changes.

using Spire.Xls;

Workbook workbook = new Workbook();
workbook.LoadFromFile("QuarterlyReportGenerator.xlsm");

IVbaProject vbaProject = workbook.VbaProject;

// Update macro logic
IVbaModule module = vbaProject.Modules["ReportModule"];  // Or use index if name is unknown
module.SourceCode = module.SourceCode.Replace(
    "\"North\", \"South\", \"East\", \"West\", \"Central\"",
    "\"North America\", \"Europe\", \"Asia Pacific\", \"Latin America\", \"Middle East\"");

// Update project metadata
// For protected VBA projects, passwords are required to modify the project-level metadata
vbaProject.Password = "securepassword";
vbaProject.Description = "Updated report logic with global regions";
vbaProject.Name = "UpdatedReportGenerator";

workbook.SaveToFile("UpdatedReportGenerator.xlsm", FileFormat.Version2016);
workbook.Dispose();

Below is a preview of the updated macro code:

Edit Macros in Excel Using C#

Spire.XLS treats macro code as editable text within a module, so updates are typically done by modifying the existing source and saving the workbook.

If you need to convert legacy .xls files to .xlsm format while preserving macros, see How to Convert XLS to XLSM and Maintain Macros Using C#.

Remove Macros

To remove macros, delete modules from the VBA project. This effectively removes all macro logic from the workbook.

using Spire.Xls;
using Spire.Xls.Core.Spreadsheet;

Workbook workbook = new Workbook();
workbook.LoadFromFile("LegacyReport.xlsm");

IVbaProject vbaProject = workbook.VbaProject;

// Remove specific module by its name
vbaProject.Modules.Remove("ReportModule");

// Or remove a module by its index
vbaProject.Modules.RemoveAt(0);

// Remove all modules
vbaProject.Modules.Clear();

workbook.SaveToFile("CleanReport.xlsm", FileFormat.Version2016);
workbook.Dispose();

After removing all modules, the workbook no longer contains executable VBA code, making it equivalent to a macro-free Excel file.

Alternatively, converting a macro-enabled Excel file to .xlsx will remove all macros, since the .xlsx format does not support VBA code.


Common Pitfalls When Working with Excel Macros

File Format Requirements

Macros require macro-enabled formats such as .xlsm, .xls, or .xlsb. The .xlsx format does not support VBA code. Always save files with the appropriate extension.

Encoding Issues

VBA code uses specific encoding (typically CodePage 1252 for Western languages). When working with international characters, ensure the CodePage is set correctly before writing macro code.

Common CodePage values include:

  • 1252 – English / Western European (default in many environments)
  • 936 – Simplified Chinese (GBK)
  • 950 – Traditional Chinese (Big5)
  • 932 – Japanese (Shift-JIS)
  • 65001 – UTF-8 (⚠️ limited support in VBA, may cause compatibility issues)

Macro Security Settings

Excel macro security settings may prevent macros from running. When distributing macro-enabled files, consider adding instructions for enabling macros or digitally signing the VBA project.

Excel Version Compatibility

VBA code written for newer Excel versions may not work correctly in older versions. Test macros across target Excel versions to ensure compatibility.


Conclusion

C# provides robust capabilities for managing Excel macros programmatically. By using Spire.XLS for .NET, developers can add, read, edit, and remove VBA code directly inside Excel files without requiring Excel installation.

This approach focuses on managing macro code rather than executing it, making it ideal for automated workflows, backend services, and large-scale document processing.

To test these features without limitations, you can apply for a free temporary license of Spire.XLS for .NET.


Frequently Asked Questions (FAQ)

Can C# add VBA macros without Microsoft Excel?

Yes. Libraries such as Spire.XLS for .NET allow you to manipulate VBA projects directly without requiring Excel installation.

What format is required for Excel macros?

Macros require macro-enabled formats such as .xlsm, .xls, .xlsb, or .xltm (for templates). The .xlsx format does not support VBA code.

Can I edit existing macros in Excel using C#?

Yes. You can access VBA modules and modify their source code programmatically to update business logic or fix issues across multiple files.

Is this approach suitable for server environments?

Yes. Since it does not rely on Microsoft Excel, this approach is ideal for backend services, automated systems, and cloud-based applications.

Can I read macro code from password-protected Excel files?

It depends on the type of protection applied to the Excel file.

  • Workbook protection (file password): You must provide the password (e.g., via Workbook.OpenPassword) when loading the file before accessing its contents.
  • VBA project protection: Reading macro code is generally allowed, but modifying project-level properties (such as name or description) requires the VBA project password.

Additionally, if the Excel file is digitally signed, any modification to the document (including macros or metadata) will invalidate the signature.

Content Preview:

Custom fonts play a key role in enhancing visual presentation and improving the user experience in modern web-based editors. Whether you’re building an enterprise document platform or integrating an editor into your web application, font customization directly affects readability, branding, and overall usability.

Spire.OfficeJS is a powerful browser-based office solution that allows developers to embed document editing capabilities—such as Word, Excel, and PowerPoint—directly into web applications, without requiring local Office installations. It supports both direct deployments using the product package scripts and integration with frontend frameworks like React, Vue, or Angular.

In practice, while the editor comes with a set of default fonts, most projects require adding custom fonts to meet branding or multilingual needs. Therefore, this guide is divided into two parts: one focuses on adding fonts using the product package scripts, and the other covers how to integrate fonts within frontend frameworks for a complete and flexible setup.

Part 1. Adding Custom Fonts in Script-Based Deployment (Product Package)

If you are using the product package editor directly, the process of adding fonts will be much easier. This part will be divided into two parts to show you how to add fonts on your Windows system or Linux system.

Download the Spire.OfficeJS Package

To begin with, you should make sure that you have downloaded the Spire.OfficeJS product package on your computer. If not, you can go to the official download link and save it to run smoothly.

Windows Systems

For Windows-based deployment servers, follow these steps:

Step 1. Add Font Files

First, copy and save the font files into the "generateFonts\fonts" folder on your server.

add the new font file to the fonts folder

Step 2. Run the Font Generation Script

Go back to the OfficeJS product file folder and double-click the "run_genallfonts.bat" script. This will register the new fonts with the editor service. Wait for the script to run over.

run font generation sript

Step 3. Refresh the Editor

Wait for the script to run over and then open your editor in a browser and press "Ctrl + F5" to reload the page. Your new fonts should now be visible.

refresh the editor to check the new added font

Linux (x86_64) Systems

Linux users need to ensure certain dependencies before running the font scripts:

Step 1. Install Required Libraries

Before running the font generation script, ensure that the required dependencies like libgdiplus and libicu are installed on your system.

Step 2. Add Font Files

Copy your custom font files (such as .ttf or .otf) into the following directory on your deployment server: generateFonts/fonts.

Step 3. Run the Font Generation Script

Execute the run_genallfonts.sh shell script to generate fonts in your Linux editor.

Step 4. Run or Refresh the Editor

After the script finishes, open or refresh the editor in your browser to see the newly added fonts.

Part 2. Integrating Custom Fonts in Frontend Frameworks like React

For developers using modern frontend frameworks like Vue, React, or Angular, you can integrate the newly generated fonts directly into your web application. The tutorial in this post takes React framework as an example.

Start building your React program with Spire.OfficeJS with this tutorial: [How to Integrate Spire.OfficeJS into a React Application.

Step-by-Step process to integrate fonts in React framework:

Step 1. Execute Font Generation Script

Use the Windows or Linux process described above to generate fonts.

Step 2. Copy Fonts Folder

First, locate the web\fontsweb folder where the generated fonts are stored and delete the existing "fontsweb" folder in your frontend project. Then, copy the new "fontsweb" folder into your project directory.

replace the fontsweb folder with a new file folder included the new font

Step 3. Update Script Files

Run "genallfonts.bat" mentioned in Part 1. Copy the generated SupFonts.js from "web > service > spirecommon" folder into your project to ensure the editor recognizes the new fonts.

replace supfonts in your react application

Step 4. Update Font Thumbnails Copy and paste fonts_thumbnail.png and fonts_thumbnail@2x.png into your project.

replace fonts thumbnail in your react application

Step 5. Refresh Your Browser Open your web application and reload the page to confirm that the editor displays all new fonts.

comparison of adding the new fonts to your react application

Common Troubleshooting for Font Integration

After adding custom fonts to your editor, it’s important to follow best practices to ensure smooth management and consistent performance across both server and frontend environments. Proper organization and verification can save time and prevent unexpected issues when working with multiple fonts or deploying across different browsers.

Below are some common issues users may encounter and recommended solutions:

  • Organize Font Files: Keep a clear folder structure for server scripts (generateFonts/fonts) and frontend projects (web/fontsweb) to avoid confusion or missing files.
  • Version Control: Use versioning for font files to prevent accidental overwrites and maintain consistency across updates.
  • Test Across Browsers: Fonts may display differently in Chrome, Firefox, Safari, and Edge. Always check their appearance in each browser.
  • Document Dependencies: On Linux systems, ensure all required libraries (libgdiplus, libicu) are installed before running scripts to avoid failures.
  • Check Font File Integrity: If issues persist, some font files may be corrupted or incompatible. In this case, add fonts in smaller batches to identify and remove problematic files.

Final Words

Adding custom fonts in Spire.OfficeJS is a simple yet powerful way to enhance the visual appeal and usability of your web-based editor. By following the steps above, users can create a consistent and professional editing experience whether they are using product package scripts on Windows or Linux, or frontend frameworks like React.

Proper organization, testing across browsers, and careful handling of font files will help prevent common issues and ensure smooth operation. Start adding your custom fonts today to give your editor a more flexible, branded, and user-friendly typography system.

Apply for License

To remove the evaluation message from generated documents or lift feature limitations, contact us to obtain a 30-day temporary license.

Tutorial on How to Import Excel Data to Python

Importing an Excel file in Python typically involves more than just reading the file. In most cases, the data needs to be converted into Python structures such as lists, dictionaries, or other formats that can be directly used in your application.

This transformation step is important because Excel data is usually stored in a tabular format, while Python applications often require structured data for processing, integration, or storage. Depending on how the data will be used, it may be represented as a list for sequential processing, a dictionary for field-based access, custom objects for structured modeling, or a database for persistent storage.

This guide demonstrates how to import Excel file in Python and convert the data into multiple structures using Spire.XLS for Python, with practical examples for each approach.


Overall Implementation Approach and Quick Example

Importing Excel data into Python is essentially a two-step process:

  1. Load Excel file – Load the Excel file and access its raw data
  2. Transform data – Convert the data into Python structures such as lists, dictionaries, or objects

This separation is important because in real-world applications, simply reading Excel is not enough—the data must be transformed into a format that can be processed, stored, or integrated into systems.

Key Components

When importing Excel data using Spire.XLS for Python, the following components are involved:

  • Workbook – Represents the entire Excel file and is responsible for loading data from disk
  • Worksheet – Represents a single sheet within the Excel file
  • CellRange – Represents a group of cells that contain actual data
  • Data Transformation Layer – Your Python logic that converts cell values into target structures

Data Flow Overview

The typical workflow looks like this:

Excel File → Workbook → Worksheet → CellRange → Python Data Structure

Understanding this pipeline helps you design flexible import logic for different scenarios.

Quick Example: Import Excel File in Python

Before running the example, install Spire.XLS for Python using pip:

pip install spire.xls

If needed, you can also download Spire.XLS for Python manually and include it in your project.

The following example shows the simplest way to import Excel data into Python:

from spire.xls import *

workbook = Workbook()
workbook.LoadFromFile("SalesReport.xlsx")

data = []
sheet = workbook.Worksheets[0]

# Get the used cell range
cellRange = sheet.AllocatedRange

# Get the data from the first row
for col in range(cellRange.Columns.Count):
    data.append(sheet.Range[1, col +1].Value)

print(data)

workbook.Dispose()

Below is a preview of the data imported from the Excel file:

Import Data from Excel File in Python

This minimal example demonstrates the fundamental workflow: initialize a workbook, load the Excel file, access the worksheet and cell data, and then dispose of the workbook to release resources.

For more advanced scenarios, such as reading Excel files from memory or handling file streams, see how to import Excel data from a stream in Python.


Import Excel Data in Python as a List

One of the simplest ways to import Excel data in Python is to convert it into a list of rows. This structure is useful for iteration and basic data processing.

Example

from spire.xls import *

# Load the Workbook
workbook = Workbook()
workbook.LoadFromFile("SalesReport.xlsx")

# Get the used range in the first worksheet
sheet = workbook.Worksheets[0]
cellRange = sheet.AllocatedRange

# Create a list to store the data
data = []
for row_index in range(cellRange.RowCount):
    row_data = []
    for cell_index in range(cellRange.ColumnCount):
        row_data.append(cellRange[row_index + 1, cell_index + 1].Value)
    data.append(row_data)

workbook.Dispose()

Technical Explanation

Importing Excel data as a list treats each row in the worksheet as a Python list, preserving the original row order.

How the code works:

  • A nested loop is used to traverse the worksheet in a row-first (row-major) pattern
  • The outer loop iterates through rows, while the inner loop accesses each cell
  • Index offsets (+1) are applied because Spire.XLS uses 1-based indexing

Why this design works:

  • AllocatedRange limits iteration to only populated cells, improving efficiency
  • Row-by-row extraction keeps the structure consistent with Excel’s layout
  • The intermediate row_data list ensures clean aggregation before appending

This structure is ideal for sequential processing, simple transformations, or as a base format before converting into dictionaries or objects.

If you want to load more than just text and numeric data, see How to Read Excel Files in Python for more data types.


Import Excel Data as a Dictionary in Python

If your Excel file contains headers, importing it as a dictionary provides better data organization and access by column names.

Example

from spire.xls import *

workbook = Workbook()
workbook.LoadFromFile("SalesReport.xlsx")

sheet = workbook.Worksheets[0]
cellRange = sheet.AllocatedRange

rows = list(cellRange.Rows)

headers = [cellRange[1, cell_index + 1].Value for cell_index in range(cellRange.ColumnCount)]

data_dict = []
for row in rows[1:]:
    row_dict = {}
    for i, cell in enumerate(row.Cells):
        row_dict[headers[i]] = cell.Value
    data_dict.append(row_dict)

workbook.Dispose()

Technical Explanation

Importing Excel data as a dictionary converts each row into a key-value structure using column headers.

How the code works:

  • The first row is extracted as headers
  • Each subsequent row is iterated and processed
  • Cell values are mapped to headers using their column index

Why this design works:

  • Both headers and row cells follow the same column order, enabling simple index-based mapping
  • This removes reliance on fixed column positions
  • The result is a self-descriptive structure with named fields

This method is useful when you need structured data access, such as working with JSON, APIs, or labeled datasets.


Import Excel Data into Custom Objects

For structured applications, you may need to import Excel data into Python objects to maintain type safety and encapsulate business logic.

Example

class Employee:
    def __init__(self, name, age, department):
        self.name = name
        self.age = age
        self.department = department

from spire.xls import *
from spire.xls.common import *

workbook = Workbook()
workbook.LoadFromFile("EmployeeData.xlsx")

sheet = workbook.Worksheets[0]
cellRange = sheet.AllocatedRange

employees = []
for row in list(cellRange.Rows)[1:]:
    name = row.Cells[0].Value
    age = int(row.Cells[1].Value) if row.Cells[1].Value else None
    department = row.Cells[2].Value

    emp = Employee(name, age, department)
    employees.append(emp)

workbook.Dispose()

Technical Explanation

Importing Excel data into objects maps each row to a structured class instance.

How the code works:

  • A class is defined to represent the data model
  • Each row is read and its values are extracted
  • Values are passed into the class constructor to create objects

Why this design works:

  • The constructor acts as a controlled transformation point
  • It allows validation, type conversion, or preprocessing
  • Data is no longer loosely structured, but aligned with domain logic

This is ideal for applications with clear data models, such as backend systems or business logic layers.


Import Excel Data to Database in Python

In many applications, Excel data needs to be stored in a database for persistent storage and querying.

Example

import sqlite3
from spire.xls import *

# Connect to SQLite database
conn = sqlite3.connect("sales.db")
cursor = conn.cursor()

# Create table matching the Excel structure
cursor.execute("""
CREATE TABLE IF NOT EXISTS sales (
    product TEXT,
    category TEXT,
    region TEXT,
    sales REAL,
    units_sold INTEGER
)
""")

# Load the Excel file
workbook = Workbook()
workbook.LoadFromFile("Sales.xlsx")

# Access the first worksheet
sheet = workbook.Worksheets[0]
rows = list(sheet.AllocatedRange.Rows)

# Iterate through rows (skip header row)
for row in rows[1:]:
    product = row.Cells[0].Value
    category = row.Cells[1].Value
    region = row.Cells[2].Value

    # Remove thousand-separators and convert to float
    sales_text = row.Cells[3].Value
    sales = float(str(sales_text).replace(",", "")) if sales_text else 0

    # Convert units sold to integer
    units_text = row.Cells[4].Value
    units_sold = int(units_text) if units_text else 0

    # Insert data into the database
    cursor.execute(
        "INSERT INTO sales VALUES (?, ?, ?, ?, ?)",
        (product, category, region, sales, units_sold)
    )

# Commit changes and close connection
conn.commit()
conn.close()

# Release Excel resources
workbook.Dispose()

Here is a preview of the Excel data and the SQLite database structure:

Import Excel Data to Database in Python

Technical Explanation

Importing Excel data into a database converts each row into a persistent record.

How the code works:

  • A database connection is established and a table is created
  • The table schema is aligned with the Excel structure
  • Each row is read and inserted using parameterized SQL queries

Why this design works:

  • Schema alignment ensures consistent data mapping
  • Data normalization (e.g., numeric conversion) improves compatibility
  • Parameterized queries provide safety and proper type handling

When to use this approach:

This approach is suitable for data storage, querying, and integration into larger data pipelines.

For a more detailed guide on importing Excel data into Databases, check out How to Transfer Data Between Excel Files and Databases.


Why Use Spire.XLS for Importing Excel Data

The examples in this guide use Spire.XLS for Python because it provides a clear and consistent way to access and transform Excel data. The main advantages in this context include:

  • Structured Object Model The library exposes components such as Workbook, Worksheet, and CellRange, which align directly with how Excel data is organized. This makes the data flow easier to understand and implement. See more details on Spire.XLS for Python API Reference.

  • Focused Data Access Layer Instead of handling low-level file parsing, you can work directly with cell values and ranges, allowing the import logic to focus on data transformation rather than file structure.

  • Format Compatibility It supports common Excel formats, such as XLS and XLSX, and other spreadsheet formats, such as CSV, ODS, and OOXML, enabling the same import logic to be applied across different file types.

  • No External Dependencies Excel files can be processed without requiring Microsoft Excel to be installed, which is important for backend services and automated environments.


Common Pitfalls

Incorrect File Path

Ensure the Excel file path is correct and accessible from your script. Use absolute paths or verify the current working directory.

import os
print(os.getcwd())  # Check current directory

Missing Headers

When importing as a dictionary, verify that your Excel file has headers in the first row. Otherwise, the keys will be incorrect.

Memory Management

Always dispose of the workbook object after processing to release resources, especially when processing large files.

workbook.Dispose()

Data Type Conversion

Excel cells may return different data types than expected. Validate and convert data types as needed for your application.


Import vs Read Excel in Python

In Python, "reading" and "importing" Excel files refer to related but distinct steps in data processing.

Read Excel focuses on accessing raw file content. This typically involves retrieving cell values, rows, or specific ranges without changing how the data is structured.

Import Excel includes both reading and transformation. After extracting the data, it is converted into structures such as lists, dictionaries, objects, or database records so that it can be used directly within an application.

In practice, reading is a subset of importing. The distinction lies in the goal—reading retrieves data, while importing prepares it for use.


Conclusion

Importing Excel file in Python is not just about reading data—it's about converting it into structures that your application can use effectively. In this guide, you learned how to import Excel file in Python as a list, convert Excel data into dictionaries, map Excel data into Python objects, and import Excel data into a database.

With Spire.XLS for Python, you can easily import Excel data into different structures with minimal code. The library provides a consistent API for handling various Excel formats and complex content, making it suitable for a wide range of data processing scenarios.

To evaluate the full performance of Spire.XLS for Python, you can apply for a 30 day trial license.


FAQ

What does it mean to import Excel file in Python?

Importing Excel means converting Excel data into Python structures such as lists, dictionaries, or databases for further processing and integration into your applications.

How do I import Excel data into Python?

You can use libraries like Spire.XLS for Python to load Excel files and convert their content into usable Python data structures. The process involves loading the workbook, accessing the worksheet, and iterating through cells to extract data.

Can I import Excel data into a database using Python?

Yes, you can read Excel data and insert it into databases like SQLite, MySQL, or PostgreSQL using Python. This approach is commonly used for data migration and backend system integration.

What is the best structure for importing Excel data?

The best structure depends on your use case. Lists are suitable for simple iteration, dictionaries for structured data access by column names, objects for type safety and business logic, and databases for persistent storage and querying.

Do I need Microsoft Excel installed to import Excel files in Python?

No, libraries like Spire.XLS for Python work independently and do not require Microsoft Excel to be installed on the system.

page 42