PDF documents may occasionally include blank pages. These pages can affect the reading experience, increase the file size and lead to paper waste during printing. To improve the professionalism and usability of a PDF document, detecting and removing blank pages is an essential step.

This article shows how to accurately detect and remove blank pages—including those that appear empty but actually contain invisible elements—using Python, Spire.PDF for Python, and Pillow.

Install Required Libraries

This tutorial requires two Python libraries:

  • Spire.PDF for Python: Used for loading PDFs and detecting/removing blank pages.
  • Pillow: A library for image processing that helps detect visually blank pages, which may contain invisible content.

You can easily install both libraries using pip:

pip install Spire.PDF Pillow

Need help installing Spire.PDF? Refer to this guide:

How to Install Spire.PDF for Python on Windows

How to Effectively Detect and Remove Blank Pages from PDF Files in Python

Spire.PDF provides a method called PdfPageBase.IsBlank() to check if a page is completely empty. However, some pages may appear blank but actually contain hidden content like white text, watermarks, or background images. These cannot be reliably detected using the PdfPageBase.IsBlank() method alone.

To ensure accuracy, this tutorial adopts a two-step detection strategy:

  • Use the PdfPageBase.IsBlank() method to identify and remove fully blank pages.
  • Convert non-blank pages to images and analyze them using Pillow to determine if they are visually blank.

⚠️ Important:

If you don’t use a valid license during the PDF-to-image conversion, an evaluation watermark will appear on the image, potentially affecting the blank page detection.

Contact the E-iceblue sales team to request a temporary license for proper functionality.

Steps to Detect and Remove Blank Pages from PDF in Python

Follow these steps to implement blank page detection and removal in Python:

1. Define a custom is_blank_image() Method

This custom function uses Pillow to check whether the converted image of a PDF page is blank (i.e., if all pixels are white).

2. Load the PDF Document

Load the PDF using the PdfDocument.LoadFromFile() method.

3. Iterate Through Pages

Loop through each page to check if it’s blank using two methods:

  • If the PdfPageBase.IsBlank() method returns True, remove the page directly.
  • If not, convert the page to an image using the PdfDocument.SaveAsImage() method and analyze it with the custom is_blank_image() method.

4. Save the Result PDF

Finally, save the PDF with blank pages removed using the PdfDocument.SaveToFile() method.

Code Example

  • Python
import io
from spire.pdf import PdfDocument
from PIL import Image

# Apply the License Key
License.SetLicenseKey("License-Key")

# Custom function: Check if the image is blank (whether all pixels are white)
def is_blank_image(image):
        # Convert to RGB mode and then get the pixels
        img = image.convert("RGB")
        # Get all pixel points and check if they are all white
        white_pixel = (255, 255, 255)
        return all(pixel == white_pixel for pixel in img.getdata())

# Load the PDF document
pdf = PdfDocument()
pdf.LoadFromFile("Sample1111.pdf")

# Iterate through each page in reverse order to avoid index issues when deleting
for i in range(pdf.Pages.Count - 1, -1, -1):
    page = pdf.Pages[i]
    # Check if the current page is completely blank
    if page.IsBlank():
        # If it's completely blank, remove it directly from the document
        pdf.Pages.RemoveAt(i)
    else:
        # Convert the current page to an image
        with pdf.SaveAsImage(i) as image_data:
            image_bytes = image_data.ToArray()
            pil_image = Image.open(io.BytesIO(image_bytes))
            # Check if the image is blank
            if is_blank_image(pil_image):
                # If it's a blank image, remove the corresponding page from the document
                pdf.Pages.RemoveAt(i)

# Save the resulting PDF
pdf.SaveToFile("RemoveBlankPages.pdf")
pdf.Close()

Python Find and Remove Blank Pages from PDF

Frequently Asked Questions (FAQs)

Q1: What is considered a blank page in a PDF file?

A: A blank page may be truly empty or contain hidden elements such as white text, watermarks, or transparent objects. This solution detects both types using a dual-check strategy.

Q2: Can I use this method without a Spire.PDF license?

A: Yes, you can run it without a license. However, during PDF-to-image conversion, an evaluation watermark will be added to the output images, which may affect the accuracy of blank page detection. It's best to request a free temporary license for testing.

Q3: What versions of Python are compatible with Spire.PDF?

A: Spire.PDF for Python supports Python 3.7 and above. Ensure that Pillow is also installed to perform image-based blank page detection.

Q4: Can I modify the script to only detect blank pages without deleting them?

A: Absolutely. Just remove or comment out the pdf.Pages.RemoveAt(i) line and use print() or logging to list detected blank pages for further review.

Conclusion

Removing unnecessary blank pages from PDF files is an important step in optimizing documents for readability, file size, and professional presentation. With the combined power of Spire.PDF for Python and Pillow, developers can precisely identify both completely blank pages and pages that appear empty but contain invisible content. Whether you're generating reports, cleaning scanned files, or preparing documents for print, this Python-based solution ensures clean and efficient PDFs.

Get a Free License

To fully experience the capabilities of Spire.PDF for Python without any evaluation limitations, you can request a free 30-day trial license.

When working with Excel, you may sometimes need to protect critical data while allowing users to edit other parts of the worksheet. This is especially important for scenarios where certain formulas, headers, or reference values must remain unchanged to ensure data integrity. By locking specific areas, you can prevent accidental modifications, maintain consistency, and control access to key information within the spreadsheet. In this article, you will learn how to lock cells, rows, and columns in Excel in React using JavaScript and the Spire.XLS for JavaScript library.

Install Spire.XLS for JavaScript

To get started with locking cells, rows, and columns in Excel files within a React application, you can either download Spire.XLS for JavaScript from our website or install it via npm with the following command:

npm i spire.xls

After that, copy the "Spire.Xls.Base.js" and "Spire.Xls.Base.wasm" files to the public folder of your project. Additionally, include the required font files to ensure accurate and consistent text rendering.

For more details, refer to the documentation: How to Integrate Spire.XLS for JavaScript in a React Project

Lock Cells in Excel

Spire.XLS for JavaScript offers the Worksheet.Range.get().Style.Locked property, allowing you to protect critical data cells while enabling edits to the rest of the worksheet. The detailed steps are as follows.

  • Create a Workbook object using the wasmModule.Workbook.Create() method.
  • Load a sample Excel file using the Workbook.LoadFromFile() method.
  • Get the first worksheet using the Workbook.Worksheets.get() method.
  • Unlock all cells in the used range of the worksheet by setting the Worksheet.Range.Style.Locked property to "false".
  • Set text for specific cells using the Worksheet.Range.get().Text property and then lock them by setting the Worksheet.Range.get().Style.Locked property to "true".
  • Protect the worksheet with a password using the Worksheet.Protect() method.
  • Save the result file using the Workbook.SaveToFile() method.
  • JavaScript
import React, { useState, useEffect } from 'react';

function App() {

  // State to hold the loaded WASM module
  const [wasmModule, setWasmModule] = useState(null);

  // useEffect hook to load the WASM module when the component mounts
  useEffect(() => {
    const loadWasm = async () => {
      try {

        // Access the Module and spirexls from the global window object
        const { Module, spirexls } = window;

        // Set the wasmModule state when the runtime is initialized
        Module.onRuntimeInitialized = () => {
          setWasmModule(spirexls);
        };
      } catch (err) {

        // Log any errors that occur during loading
        console.error('Failed to load WASM module:', err);
      }
    };

    // Create a script element to load the WASM JavaScript file

    const script = document.createElement('script');
    script.src = `${process.env.PUBLIC_URL}/Spire.Xls.Base.js`;
    script.onload = loadWasm;

    // Append the script to the document body
    document.body.appendChild(script);

    // Cleanup function to remove the script when the component unmounts
    return () => {
      document.body.removeChild(script);
    };
  }, []); 

  // Function to lock specific cells in Excel
  const LockExcelCells = async () => {
    if (wasmModule) {
      // Load the ARIALUNI.TTF font file into the virtual file system (VFS)
      await wasmModule.FetchFileToVFS('ARIALUNI.TTF', '/Library/Fonts/', `${process.env.PUBLIC_URL}/`);
      
      // Load the input Excel file into the virtual file system (VFS)
      const inputFileName = 'Sample.xlsx';
      await wasmModule.FetchFileToVFS(inputFileName, '', `${process.env.PUBLIC_URL}/`);
      
      // Create a new workbook
      const workbook = wasmModule.Workbook.Create();
      // Load the Excel file from the virtual file system
      workbook.LoadFromFile({fileName: inputFileName});

      // Get the first worksheet
      let sheet = workbook.Worksheets.get(0);

      // Unlock all cells in the used range of the worksheet
      sheet.Range.Style.Locked = false;

      // Lock a specific cell in the worksheet
      sheet.Range.get("A1").Text = "Locked";
      sheet.Range.get("A1").Style.Locked = true;

      // Lock a specific cell range in the worksheet
      sheet.Range.get("C1:E3").Text = "Locked";
      sheet.Range.get("C1:E3").Style.Locked = true;

      // Protect the worksheet with a password
      sheet.Protect({password: "123", options: wasmModule.SheetProtectionType.All});

      let outputFileName = "LockCells.xlsx";
      // Save the resulting file
      workbook.SaveToFile({ fileName: outputFileName, version: wasmModule.ExcelVersion.Version2013 });
      
      // Read the saved file and convert it to a Blob object
      const modifiedFileArray = wasmModule.FS.readFile(outputFileName);
      const modifiedFile = new Blob([modifiedFileArray], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
      
      // Create a URL for the Blob and initiate the download
      const url = URL.createObjectURL(modifiedFile);
      const a = document.createElement('a');
      a.href = url;
      a.download = outputFileName;
      document.body.appendChild(a);
      a.click(); 
      document.body.removeChild(a); 
      URL.revokeObjectURL(url); 

      // Clean up resources used by the workbooks
      workbook.Dispose();
    }
  };

  return (
    <div style={{ textAlign: 'center', height: '300px' }}>
      <h1>Lock Specific Cells in Excel Using JavaScript in React</h1>
      <button onClick={LockExcelCells} disabled={!wasmModule}>
        Lock
      </button>
    </div>
  );
}

export default App;	

Run the code to launch the React app at localhost:3000. Once it's running, click on the "Lock" button to lock specific cells in the Excel file:

Run the code to launch the React app

Upon opening the output Excel sheet and attempting to edit the protected cells, a dialog box will appear, notifying you that the cell you're trying to change is on a protected sheet:

Lock Cells in Excel

Lock Rows in Excel

If you need to preserve row-based data, such as headers or summaries, you can lock entire rows using the Worksheet.Rows.get().Style.Locked property in Spire.XLS for JavaScript. The detailed steps are as follows.

  • Create a Workbook object using the wasmModule.Workbook.Create() method.
  • Load a sample Excel file using the Workbook.LoadFromFile() method.
  • Get the first worksheet using the Workbook.Worksheets.get() method.
  • Unlock all cells in the used range of the worksheet by setting the Worksheet.Range.Style.Locked property to "false".
  • Set text for a specific row using the Worksheet.Rows.get().Text property and then lock it by setting the Worksheet.Rows.get().Style.Locked property to "true".
  • Protect the worksheet with a password using the Worksheet.Protect() method.
  • Save the result file using the Workbook.SaveToFile() method.
  • JavaScript
import React, { useState, useEffect } from 'react';

function App() {

  // State to hold the loaded WASM module
  const [wasmModule, setWasmModule] = useState(null);

  // useEffect hook to load the WASM module when the component mounts
  useEffect(() => {
    const loadWasm = async () => {
      try {

        // Access the Module and spirexls from the global window object
        const { Module, spirexls } = window;

        // Set the wasmModule state when the runtime is initialized
        Module.onRuntimeInitialized = () => {
          setWasmModule(spirexls);
        };
      } catch (err) {

        // Log any errors that occur during loading
        console.error('Failed to load WASM module:', err);
      }
    };

    // Create a script element to load the WASM JavaScript file

    const script = document.createElement('script');
    script.src = `${process.env.PUBLIC_URL}/Spire.Xls.Base.js`;
    script.onload = loadWasm;

    // Append the script to the document body
    document.body.appendChild(script);

    // Cleanup function to remove the script when the component unmounts
    return () => {
      document.body.removeChild(script);
    };
  }, []); 

  // Function to lock specific rows in Excel
  const LockExcelRows = async () => {
    if (wasmModule) {
      // Load the ARIALUNI.TTF font file into the virtual file system (VFS)
      await wasmModule.FetchFileToVFS('ARIALUNI.TTF', '/Library/Fonts/', `${process.env.PUBLIC_URL}/`);
      
      // Load the input Excel file into the virtual file system (VFS)
      const inputFileName = 'Sample.xlsx';
      await wasmModule.FetchFileToVFS(inputFileName, '', `${process.env.PUBLIC_URL}/`);
      
      // Create a new workbook
      const workbook = wasmModule.Workbook.Create();
      // Load the Excel file from the virtual file system
      workbook.LoadFromFile({fileName: inputFileName});

      // Get the first worksheet
      let sheet = workbook.Worksheets.get(0);

      // Unlock all cells in the used range of the worksheet
      sheet.Range.Style.Locked = false;

      // Lock the third row in the worksheet
      sheet.Rows.get(2).Text = "Locked";
      sheet.Rows.get(2).Style.Locked = true;

      // Protect the worksheet with a password
      sheet.Protect({password: "123", options: wasmModule.SheetProtectionType.All});

      let outputFileName = "LockRows.xlsx";
      // Save the resulting file
      workbook.SaveToFile({ fileName: outputFileName, version: wasmModule.ExcelVersion.Version2013 });
      
      // Read the saved file and convert it to a Blob object
      const modifiedFileArray = wasmModule.FS.readFile(outputFileName);
      const modifiedFile = new Blob([modifiedFileArray], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
      
      // Create a URL for the Blob and initiate the download
      const url = URL.createObjectURL(modifiedFile);
      const a = document.createElement('a');
      a.href = url;
      a.download = outputFileName;
      document.body.appendChild(a);
      a.click(); 
      document.body.removeChild(a); 
      URL.revokeObjectURL(url); 

      // Clean up resources used by the workbooks
      workbook.Dispose();
    }
  };

  return (
    <div style={{ textAlign: 'center', height: '300px' }}>
      <h1>Lock Specific Rows in Excel Using JavaScript in React</h1>
      <button onClick={LockExcelRows} disabled={!wasmModule}>
        Lock
      </button>
    </div>
  );
}

export default App;

Lock Rows in Excel

Lock Columns in Excel

To maintain the integrity of key vertical data, such as fixed identifiers or category labels, you can lock entire columns using the Worksheet.Columns.get().Style.Locked property in Spire.XLS for JavaScript. The detailed steps are as follows.

  • Create a Workbook object using the wasmModule.Workbook.Create() method.
  • Load a sample Excel file using the Workbook.LoadFromFile() method.
  • Get the first worksheet using the Workbook.Worksheets.get() method.
  • Unlock all cells in the used range of the worksheet by setting the Worksheet.Range.Style.Locked property to "false".
  • Set text for a specific column using the Worksheet.Columns.get().Text property and then lock it by setting the Worksheet.Columns.get().Style.Locked property to "true".
  • Protect the worksheet with a password using the Worksheet.Protect() method.
  • Save the result file using the Workbook.SaveToFile() method.
  • JavaScript
import React, { useState, useEffect } from 'react';

function App() {

  // State to hold the loaded WASM module
  const [wasmModule, setWasmModule] = useState(null);

  // useEffect hook to load the WASM module when the component mounts
  useEffect(() => {
    const loadWasm = async () => {
      try {

        // Access the Module and spirexls from the global window object
        const { Module, spirexls } = window;

        // Set the wasmModule state when the runtime is initialized
        Module.onRuntimeInitialized = () => {
          setWasmModule(spirexls);
        };
      } catch (err) {

        // Log any errors that occur during loading
        console.error('Failed to load WASM module:', err);
      }
    };

    // Create a script element to load the WASM JavaScript file

    const script = document.createElement('script');
    script.src = `${process.env.PUBLIC_URL}/Spire.Xls.Base.js`;
    script.onload = loadWasm;

    // Append the script to the document body
    document.body.appendChild(script);

    // Cleanup function to remove the script when the component unmounts
    return () => {
      document.body.removeChild(script);
    };
  }, []); 

  // Function to lock specific columns in Excel
  const LockExcelColumns = async () => {
    if (wasmModule) {
      // Load the ARIALUNI.TTF font file into the virtual file system (VFS)
      await wasmModule.FetchFileToVFS('ARIALUNI.TTF', '/Library/Fonts/', `${process.env.PUBLIC_URL}/`);
      
      // Load the input Excel file into the virtual file system (VFS)
      const inputFileName = 'Sample.xlsx';
      await wasmModule.FetchFileToVFS(inputFileName, '', `${process.env.PUBLIC_URL}/`);
      
      // Create a new workbook
      const workbook = wasmModule.Workbook.Create();
      // Load the Excel file from the virtual file system
      workbook.LoadFromFile({fileName: inputFileName});

      // Get the first worksheet
      let sheet = workbook.Worksheets.get(0);

      // Unlock all cells in the used range of the worksheet
      sheet.Range.Style.Locked = false;

      // Lock the fourth column in the worksheet
      sheet.Columns.get(3).Text = "Locked";
      sheet.Columns.get(3).Style.Locked = true;

      // Protect the worksheet with a password
      sheet.Protect({password: "123", options: wasmModule.SheetProtectionType.All});

      let outputFileName = "LockColumns.xlsx";
      // Save the resulting file
      workbook.SaveToFile({ fileName: outputFileName, version: wasmModule.ExcelVersion.Version2013 });
      
      // Read the saved file and convert it to a Blob object
      const modifiedFileArray = wasmModule.FS.readFile(outputFileName);
      const modifiedFile = new Blob([modifiedFileArray], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
      
      // Create a URL for the Blob and initiate the download
      const url = URL.createObjectURL(modifiedFile);
      const a = document.createElement('a');
      a.href = url;
      a.download = outputFileName;
      document.body.appendChild(a);
      a.click(); 
      document.body.removeChild(a); 
      URL.revokeObjectURL(url); 

      // Clean up resources used by the workbooks
      workbook.Dispose();
    }
  };

  return (
    <div style={{ textAlign: 'center', height: '300px' }}>
      <h1>Lock Specific Columns in Excel Using JavaScript in React</h1>
      <button onClick={LockExcelColumns} disabled={!wasmModule}>
        Lock
      </button>
    </div>
  );
}

export default App;

Lock Columns in Excel

Get a Free License

To fully experience the capabilities of Spire.XLS for JavaScript without any evaluation limitations, you can request a free 30-day trial license.

We are delighted to announce the release of Spire.Presentation for Java 10.2.2. This version enhances the conversion from PowerPoint documents to images. Moreover, some known issues are fixed successfully in this version, such as the issue that it threw "Value cannot be null" when saving a PowerPoint document. More details are listed below.

Here is a list of changes made in this release

Category ID Description
Bug SPIREPPT-2669 Fixes the issue that the shadow effect of text was lost when converting PowerPoint to images.
Bug SPIREPPT-2717 Optimizes the function of adding annotations for specific text.
Bug SPIREPPT-2718 Fixes the issue that it threw "StringIndexOutOfBoundsException" when adding annotations for specific text.
Bug SPIREPPT-2719 Fixes the issue that the effect of converting PowerPoint to images was incorrect.
Bug SPIREPPT-2722 Fixes the issue that it threw "Value cannot be null" when saving a PowerPoint document.
Click the link below to download Spire.Presentation for Java 10.2.2:

We're pleased to announce the release of Spire.Doc 13.2.3. This version optimizes the time and resource consumption when converting Word to PDF, and also adds new interfaces for reading and writing chart titles, data labels, axis, legends, data tables and other chart attributes. More details are listed below.

Here is a list of changes made in this release

Category ID Description
New feature - Adds new interfaces for reading and writing chart titles, chart data labels, chart axis, chart legends, chart data tables and other attributes.
  • ChartTitle.Text property: Sets the chart title text.
  • ChartDataLabel.ShowValue property: Sets whether the data label includes the value.
  • ChartAxis.CategoryType property: Sets the type of the horizontal axis (automatic, text, or date).
  • ChartLegend.Position property: Sets the position of the legend.
  • ChartDataTable.Show property: Sets whether to display the data table.
New feature - Namespace changes:
Spire.Doc.Formatting.RowFormat.TablePositioning->Spire.Doc.Formatting.TablePositioning
Spire.Doc.Printing.PagesPreSheet->Spire.Doc.Printing.PagesPerSheet    
New feature - Optimizes the time and resource consumption when converting Word to PDF, especially when working with large files or complex layouts.
Click the link to download Spire.Doc 13.2.3:
More information of Spire.Doc new release or hotfix:

We are excited to announce the release of the Spire.XLS for Java 15.2.1. The latest version enhances conversions from Excel to images and PDF. Besides, this update fixes the issue that the program threw a "NullPointerException" when loading an XLSX document. More details are listed below.

Here is a list of changes made in this release

Category ID Description
Bug SPIREXLS-5575 Fixes the issue that the program threw a "NullPointerException" when loading an XLSX document.
Bug SPIREXLS-5668 Fixes the issue that incorrect colors existed when converting Excel to images.
Bug SPIREXLS-5685 Fixes the issue that incomplete content displayed when converting Excel to PDF.
Click the link to download Spire.XLS for Java 15.2.1:

Ler arquivos Excel em C# é um requisito comum para muitas aplicações, seja para análise de dados, relatórios ou integração com banco de dados. Embora as bibliotecas Interop da Microsoft possam ser usadas, elas têm limitações (como exigir que o Excel esteja instalado). Em vez disso, exploraremos uma abordagem mais eficiente usando o Spire.XLS, uma biblioteca .NET que permite ler e escrever arquivos Excel sem Interop. Este artigo aborda:

Biblioteca C# .NET para Ler Excel Sem Interop

O Excel Interop da Microsoft exige que o Excel esteja instalado na máquina, tornando-o inadequado para aplicações do lado do servidor. Em vez disso, bibliotecas como o Spire.XLS oferecem uma solução leve e de alto desempenho, sem dependências do Excel.

Por que usar o Spire.XLS?

  • Nenhuma Instalação do Excel Necessária – Funciona de forma independente.
  • Suporta .NET Core & .NET Framework – Compatibilidade multiplataforma.
  • Ler/Escrever Arquivos Excel – Suporta .xls, .xlsx e .xlsm.
  • Importar para DataTable & Bancos de Dados – Integração perfeita com ADO.NET.

Instalação do Spire.XLS

Para começar, instale a biblioteca via Gerenciador de Pacotes NuGet:

Install-Package Spire.XLS

Alternativamente, você pode baixar o Spire.XLS for .NET do nosso site oficial e referenciar o arquivo DLL manualmente.

Como Ler um Arquivo Excel em C#

Esta seção demonstra como ler um arquivo Excel em C# usando a biblioteca Spire.XLS. O processo envolve carregar o arquivo, acessar planilhas e recuperar valores de células programaticamente. Isso é útil para automatizar a extração de dados, processar relatórios do Excel ou integrar dados de planilhas em aplicações.

Passo 1. Importar Namespace Necessário

Para utilizar a funcionalidade do Spire.XLS, você precisa importar seu namespace. Isso dá acesso a classes como Workbook e Worksheet, que são essenciais para operações com arquivos Excel.

  • C#
using Spire.Xls;

Passo 2. Carregar um Arquivo Excel

Para carregar um arquivo Excel, crie um objeto Workbook e chame o método LoadFromFile. Isso lê o arquivo na memória, permitindo manipulação posterior.

  • C#
Workbook wb = new Workbook();
wb.LoadFromFile("input.xlsx");

Passo 3. Obter uma Planilha Específica

Arquivos Excel podem conter várias planilhas. Você pode acessar uma planilha específica indexando a coleção Worksheets (baseada em zero). A primeira planilha está no índice 0, a segunda no 1, e assim por diante.

  • C#
Worksheet sheet = wb.Worksheets[0]; //Primeira planilha

Passo 4. Recuperar Valor de uma Célula Específica

Para recuperar o valor de uma célula, use a propriedade CellRange.Value. Especifique os índices de linha e coluna (começando em 1) para localizar a célula. Isso é útil para extrair dados estruturados como cabeçalhos ou registros individuais.

  • C#
CellRange cell = sheet.Range[1, 1]; // Linha1, Coluna 1 (A1)
string value = cell.Value;

Abaixo está um exemplo completo de leitura de dados de uma planilha inteira e impressão no console:

  • C#
using Spire.Xls;

namespace ReadExcelData
{
    class Program
    {
        static void Main(string[] args)
        {
            // Create a Workbook object
            Workbook wb = new Workbook();

            // Load an existing Excel file
            wb.LoadFromFile("C:\\Users\\Administrator\\Desktop\\Input.xlsx");

            // Get the first worksheet
            Worksheet sheet = wb.Worksheets[0];

            // Get the cell range containing data
            CellRange locatedRange = sheet.AllocatedRange;

            // Iterate through the rows
            for (int i = 0; i < locatedRange.Rows.Length; i++)
            {
                // Iterate through the columns
                for (int j = 0; j < locatedRange.Rows[i].ColumnCount; j++)
                {
                    // Get data of a specific cell
                    string cellValue = locatedRange[i + 1, j + 1].Value?.ToString() ?? "N/A";

                    // Align output with a width of 22
                    Console.Write($"{cellValue,-22}");
                }
                Console.WriteLine();
            }
        }
    }
}

Resultado:

ler arquivo excel em c#

Ler Dados do Excel para um DataTable

Exportar dados do Excel para um DataTable permite uma integração perfeita com controles de UI como DataGridView ou processamento de dados de backend. O Spire.XLS simplifica este processo com seu método integrado ExportDataTable(), que converte automaticamente os dados da planilha em um DataTable estruturado, preservando os cabeçalhos das colunas e os tipos de dados.

Passo 1. Importar Namespace Necessário

Inclua o namespace Spire.XLS para acessar as classes essenciais.

  • C#
using Spire.Xls;

Passo 2. Criar um Formulário e Evento de Clique de Botão

Crie um formulário (por exemplo, Form1) e adicione um botão com um manipulador de eventos para ler o arquivo Excel.

  • C#
public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        // O código irá aqui
    }
}

Passo 3. Carregar o Workbook

Dentro do evento de clique do botão, crie um objeto Workbook e carregue o arquivo Excel.

  • C#
Workbook wb = new Workbook();
wb.LoadFromFile("C:\\Users\\Administrator\\Desktop\\Input.xlsx");

Passo 4. Exportar Dados para DataTable

Acesse uma planilha específica por seu índice e exporte seus dados para um DataTable usando o método ExportDataTable.

  • C#
DataTable dataTable = wb.Worksheets[0].ExportDataTable();

Passo 5. Vincular Dados ao DataGridView

Supondo que você tenha um controle DataGridView em seu formulário, vincule o DataTable ao DataGridView para exibir os dados.

  • C#
dataGridView1.DataSource = dataTable;

O seguinte é o código completo para ler dados de um arquivo Excel em um DataTable e exibi-lo em um controle DataGridView do Windows Forms:

  • C#
using Spire.Xls;
using System.Data;

namespace ReadExcelIntoDataTable
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            // Create a Workbook object
            Workbook wb = new Workbook();

            // Load an existing Excel file
            wb.LoadFromFile("C:\\Users\\Administrator\\Desktop\\Input.xlsx");

            // Get the first worksheet
            Worksheet sheet = wb.Worksheets[0];

            // Export data from worksheet into a DataTable
            DataTable dataTable = sheet.ExportDataTable();

            // Bind DataTable to DataGridView
            dataGridView1.DataSource = dataTable;

            // Dispose resources
            wb.Dispose();
        }
    }
}

Resultado:

Os dados do Excel são exibidos em uma tabela MySQL.

Ler Dados do Excel para um Banco de Dados

A integração de dados do Excel com um banco de dados pode otimizar o gerenciamento de dados. Abaixo, vamos percorrer o processo de leitura de um arquivo Excel e importação de seu conteúdo para um banco de dados MySQL. Este método é ideal para automatizar a migração de dados, relatórios ou sincronizar dados do Excel com um banco de dados estruturado.

Passo 1. Instalar a Biblioteca de Dados MySQL

Para interagir com bancos de dados MySQL em suas aplicações .NET, você precisará instalar a biblioteca MySql.Data. Este pacote NuGet fornece as classes e métodos necessários para conectar e manipular bancos de dados MySQL.

  • C#
Install-Package MySql.Data

Passo 2. Importar Namespaces Necessários

Antes de trabalhar com arquivos Excel e MySQL, você deve incluir os namespaces necessários. O Spire.XLS é usado para operações com Excel, enquanto o MySql.Data.MySqlClient permite a conectividade com o banco de dados MySQL.

  • C#
using Spire.Xls;
using MySql.Data.MySqlClient;

Passo 3. Extrair Cabeçalhos e Dados do Excel

O trecho de código a seguir demonstra como extrair cabeçalhos e dados do arquivo Excel. Os cabeçalhos são limpos para evitar conflitos de nomenclatura de colunas do MySQL, enquanto os dados são armazenados em um formato estruturado para inserção posterior.

  • C#
// Create a Workbook object
Workbook wb = new Workbook();

// Load an Excel document
wb.LoadFromFile("C:\\Users\\Administrator\\Desktop\\Input.xlsx");

// Get a specific sheet
Worksheet sheet = wb.Worksheets[0];

// Retrieve headers
List<string> headers = new List<string>();
for (int col = 1; col <= sheet.LastColumn; col++)
{
    string header = sheet.Range[1, col].Value?.ToString();
    // Removing spaces to avoid conflicts with MySQL column names
    string cleanHeader = header?.Replace(" ", "");
    headers.Add($"`{cleanHeader}`");
}

// Retrieve data
List<List<string>> data = new List<List<string>>();
for (int row = 2; row <= sheet.LastRow; row++) {
    List<string> record = new List<string>();
    for (int col = 1; col <= sheet.LastColumn; col++)
    {
        record.Add(sheet.Range[row, col].Value?.ToString() ?? string.Empty);
    }
    data.Add(record);
}

Passo 4. Conectar a um Banco de Dados MySQL

Uma conexão com o banco de dados MySQL é estabelecida usando uma string de conexão, que inclui detalhes do servidor, credenciais e o nome do banco de dados de destino. A instrução using garante a liberação adequada dos recursos.

  • C#
string connectionString = "server=localhost;user=root;password=yourpassword;database=yourdatabase;";
using (MySqlConnection connection = new MySqlConnection(connectionString))
{
    connection.Open();
    // A conexão está estabelecida; execute as operações do banco de dados aqui
}

Passo 5. Criar Dinamicamente uma Tabela no MySQL

Este passo gera dinamicamente uma tabela MySQL com colunas que correspondem aos cabeçalhos do Excel. Por simplicidade, todas as colunas são definidas como VARCHAR(255), mas os tipos de dados podem ser ajustados com base nos requisitos.

  • C#
// Create a table with dynamic columns based on headers
List<string> columns = new List<string>();
foreach (string header in headers)
{
    // Assuming all header values are VARCHAR for simplicity; adjust types as needed
    columns.Add($"{header} VARCHAR(255)");
}

// Create a table in database
string columnsSql = string.Join(", ", columns);
string createTableQuery = $ @"
    CREATE TABLE IF NOT EXISTS my_table (
        id INT AUTO_INCREMENT PRIMARY KEY,
        {columnsSql}
)";

// Execute the create table query
using (MySqlCommand createCommand = new MySqlCommand(createTableQuery, connection))
{
    createCommand.ExecuteNonQuery();
}

Passo 6. Preencher a Tabela com Dados

Os dados extraídos do Excel são inseridos na tabela MySQL usando consultas parametrizadas para prevenir injeção de SQL. Cada linha do arquivo Excel é mapeada para um registro de banco de dados correspondente.

  • C#
// Prepare the SQL INSERT statement
string placeholders = string.Join(", ", new string[headers.Count].Select(h => "?"));
string insertQuery = $"INSERT INTO my_table ({string.Join(", ", headers.Select(h => h.Trim('`')))}) VALUES ({placeholders})";

// Insert data into the table
foreach (List<string> record in data)
{
    using (MySqlCommand insertCommand = new MySqlCommand(insertQuery, connection))
    {
        for (int i = 0; i < record.Count; i++)
        {
            insertCommand.Parameters.AddWithValue($" @2024\本地文件打包__20180302\Spire.Web\trunk\src\website\components\com_virtuemart\themes\default\templates\browse\includes\browse_searchparameter_form.tpl.php{i}", record[i]);
        }
        insertCommand.ExecuteNonQuery();
    }
}

Aqui está o código completo para importar dados de um arquivo Excel para uma tabela MySQL:

  • C#
using Spire.Xls;
using MySql.Data.MySqlClient;

namespace ExcelToMySQL
{
    class Program
    {
        static void Main(string[] args)
        {
            // Create a Workbook object
            Workbook wb = new Workbook();

            // Load an Excel document
            wb.LoadFromFile("C:\\Users\\Administrator\\Desktop\\Input.xlsx");

            // Get a specific sheet
            Worksheet sheet = wb.Worksheets[0];

            // Retrieve headers
            List<string> headers = new List<string>();
            for (int col = 1; col <= sheet.LastColumn; col++)
            {
                string header = sheet.Range[1, col].Value?.ToString();
                // Removing spaces to avoid conflicts with MySQL column names
                string cleanHeader = header?.Replace(" ", "");
                headers.Add($"`{cleanHeader}`");
            }

            // Retrieve data
            List<List<string>> data = new List<List<string>>();
            for (int row = 2; row <= sheet.LastRow; row++)
            {
                List<string> record = new List<string>();
                for (int col = 1; col <= sheet.LastColumn; col++)
                {
                    record.Add(sheet.Range[row, col].Value?.ToString() ?? string.Empty);
                }
                data.Add(record);
            }

            // Establish a connection to the MySQL database
            string connectionString = "server=localhost;user=root;password=admin;database=excel_db;";
            using (MySqlConnection connection = new MySqlConnection(connectionString))
            {
                connection.Open();

                // Create a table with dynamic columns based on headers
                List<string> columns = new List<string>();
                foreach (string header in headers)
                {
                    // Assuming all header values are VARCHAR for simplicity; adjust types as needed
                    columns.Add($"{header} VARCHAR(255)");
                }

                // Create a table in database
                string columnsSql = string.Join(", ", columns);
                string createTableQuery = $ @"
                    CREATE TABLE IF NOT EXISTS my_table (
                        id INT AUTO_INCREMENT PRIMARY KEY,
                        {columnsSql}
                    )";

                // Execute the create table query
                using (MySqlCommand createCommand = new MySqlCommand(createTableQuery, connection))
                {
                    createCommand.ExecuteNonQuery();
                }

                // Prepare the SQL INSERT statement
                string placeholders = string.Join(", ", new string[headers.Count].Select(h => "?"));
                string insertQuery = $"INSERT INTO my_table ({string.Join(", ", headers.Select(h => h.Trim('`')))}) VALUES ({placeholders})";

                // Insert data into the table
                foreach (List<string> record in data)
                {
                    using (MySqlCommand insertCommand = new MySqlCommand(insertQuery, connection))
                    {
                        for (int i = 0; i < record.Count; i++)
                        {
                            insertCommand.Parameters.AddWithValue($" @2024\本地文件打包__20180302\Spire.Web\trunk\src\website\components\com_virtuemart\themes\default\templates\browse\includes\browse_searchparameter_form.tpl.php{i}", record[i]);
                        }
                        insertCommand.ExecuteNonQuery();
                    }
                }
            }

            Console.WriteLine("Dados exportados com sucesso!");
        }
    }
}

Resultado:

Os dados do Excel são exibidos em uma tabela MySQL.

Conclusão

Ler arquivos Excel em C# nunca foi tão fácil, graças a bibliotecas como o Spire.XLS. Este guia o orientou no processo de carregar arquivos Excel, ler seu conteúdo e até mesmo importar os dados para um banco de dados MySQL. Com essas técnicas, você pode aprimorar significativamente as capacidades de manipulação de dados de suas aplicações.

Perguntas Frequentes

Q1: Posso ler arquivos Excel protegidos por senha?

R: Sim, o Spire.XLS suporta a leitura de arquivos Excel criptografados usando:

  • C#
wb.OpenPassword = "psd";
wb.LoadFromFile("file.xlsx");

Q2: Como leio os resultados da fórmula em vez da própria fórmula?

R: Você tem duas opções para recuperar os resultados da fórmula:

Para células individuais:

Verifique se uma célula contém uma fórmula usando CellRange.HasFormula e obtenha o valor com CellRange.FormulaValue:

  • C#
CellRange cell = sheet.Range[1, 1];
if (cell.HasFormula)
{
    string result = cell.FormulaValue.ToString();
}

Para exportação em massa para DataTable:

Use Worksheet.ExportDataTable() com computedFormulaValue: true para exportar valores calculados:

  • C#
DataTable data = sheet.ExportDataTable(range, exportColumnNames: true, computedFormulaValue: true);

Q3: Como posso ler dados do Excel para um DataTable?

R: Use o método Worksheet.ExportDataTable() fornecido pelo Spire.XLS.

Q4: Como posso ler um arquivo Excel linha por linha?

R: Consulte o seguinte código:

  • C#
Workbook workbook = new Workbook();
workbook.LoadFromFile("input.xlsx");
Worksheet sheet = workbook.Worksheets[0];

for (int row = 1; row <= sheet.LastRow; row++)
{
    for (int col = 1; col <= sheet.LastColumn; col++)
    {
        string cellValue = sheet.Range[row, col].Value?.ToString() ?? string.Empty;
        Console.WriteLine(cellValue);
    }
}

Obtenha uma Licença Gratuita

Para experimentar plenamente as capacidades do Spire.XLS for .NET sem quaisquer limitações de avaliação, você pode solicitar uma licença de avaliação gratuita de 30 dias.

Veja Também

Das Lesen von Excel-Dateien in C# ist eine häufige Anforderung für viele Anwendungen, sei es für Datenanalyse, Berichterstattung oder Datenbankintegration. Während die Interop-Bibliotheken von Microsoft verwendet werden können, haben sie Einschränkungen (z. B. die Notwendigkeit, dass Excel installiert ist). Stattdessen werden wir einen effizienteren Ansatz mit Spire.XLS untersuchen, einer .NET-Bibliothek, die das Lesen und Schreiben von Excel-Dateien ohne Interop ermöglicht. Dieser Artikel behandelt:

C# .NET-Bibliothek zum Lesen von Excel ohne Interop

Microsofts Excel Interop erfordert, dass Excel auf dem Computer installiert ist, was es für serverseitige Anwendungen ungeeignet macht. Stattdessen bieten Bibliotheken wie Spire.XLS eine leichtgewichtige, hochleistungsfähige Lösung ohne Abhängigkeiten von Excel.

Warum Spire.XLS verwenden?

  • Keine Excel-Installation erforderlich – Funktioniert unabhängig.
  • Unterstützt .NET Core & .NET Framework – Plattformübergreifende Kompatibilität.
  • Excel-Dateien lesen/schreiben – Unterstützt .xls, .xlsx und .xlsm.
  • Import in DataTable & Datenbanken – Nahtlose Integration mit ADO.NET.

Installation von Spire.XLS

Um zu beginnen, installieren Sie die Bibliothek über den NuGet Package Manager:

Install-Package Spire.XLS

Alternativ können Sie Spire.XLS für .NET von unserer offiziellen Website herunterladen und die DLL-Datei manuell referenzieren.

Wie man eine Excel-Datei in C# liest

Dieser Abschnitt zeigt, wie man eine Excel-Datei in C# mit der Spire.XLS-Bibliothek liest. Der Prozess umfasst das Laden der Datei, den Zugriff auf Arbeitsblätter und das programmgesteuerte Abrufen von Zellwerten. Dies ist nützlich für die Automatisierung der Datenextraktion, die Verarbeitung von Excel-Berichten oder die Integration von Tabellenkalkulationsdaten in Anwendungen.

Schritt 1. Notwendigen Namespace importieren

Um die Funktionalität von Spire.XLS zu nutzen, müssen Sie dessen Namespace importieren. Dies ermöglicht den Zugriff auf Klassen wie Workbook und Worksheet, die für Excel-Dateioperationen unerlässlich sind.

  • C#
using Spire.Xls;

Schritt 2. Eine Excel-Datei laden

Um eine Excel-Datei zu laden, erstellen Sie ein Workbook-Objekt und rufen Sie die Methode LoadFromFile auf. Dadurch wird die Datei in den Speicher gelesen, was eine weitere Bearbeitung ermöglicht.

  • C#
Workbook wb = new Workbook();
wb.LoadFromFile("input.xlsx");

Schritt 3. Ein bestimmtes Arbeitsblatt abrufen

Excel-Dateien können mehrere Arbeitsblätter enthalten. Sie können auf ein bestimmtes Blatt zugreifen, indem Sie die Worksheets-Sammlung indizieren (nullbasiert). Das erste Blatt befindet sich am Index 0, das zweite am Index 1 und so weiter.

  • C#
Worksheet sheet = wb.Worksheets[0]; //Erstes Blatt

Schritt 4. Wert einer bestimmten Zelle abrufen

Um den Wert einer Zelle abzurufen, verwenden Sie die Eigenschaft CellRange.Value. Geben Sie die Zeilen- und Spaltenindizes (beginnend bei 1) an, um die Zelle zu lokalisieren. Dies ist nützlich zum Extrahieren strukturierter Daten wie Kopfzeilen oder einzelner Datensätze.

  • C#
CellRange cell = sheet.Range[1, 1]; // Zeile1, Spalte 1 (A1)
string value = cell.Value;

Unten finden Sie ein vollständiges Beispiel zum Lesen von Daten aus einem gesamten Arbeitsblatt und zum Ausgeben in der Konsole:

  • C#
using Spire.Xls;

namespace ReadExcelData
{
    class Program
    {
        static void Main(string[] args)
        {
            // Erstellen Sie ein Workbook-Objekt
            Workbook wb = new Workbook();

            // Laden Sie eine vorhandene Excel-Datei
            wb.LoadFromFile("C:\\Users\\Administrator\\Desktop\\Input.xlsx");

            // Holen Sie sich das erste Arbeitsblatt
            Worksheet sheet = wb.Worksheets[0];

            // Holen Sie sich den Zellbereich, der Daten enthält
            CellRange locatedRange = sheet.AllocatedRange;

            // Iterieren Sie durch die Zeilen
            for (int i = 0; i < locatedRange.Rows.Length; i++)
            {
                // Iterieren Sie durch die Spalten
                for (int j = 0; j < locatedRange.Rows[i].ColumnCount; j++)
                {
                    // Holen Sie sich die Daten einer bestimmten Zelle
                    string cellValue = locatedRange[i + 1, j + 1].Value?.ToString() ?? "N/A";

                    // Richten Sie die Ausgabe mit einer Breite von 22 aus
                    Console.Write($"{cellValue,-22}");
                }
                Console.WriteLine();
            }
        }
    }
}

Ergebnis:

Excel-Datei in C# lesen

Excel-Daten in eine DataTable einlesen

Das Exportieren von Excel-Daten in eine DataTable ermöglicht eine nahtlose Integration mit UI-Steuerelementen wie DataGridView oder der Backend-Datenverarbeitung. Spire.XLS vereinfacht diesen Prozess mit seiner integrierten Methode ExportDataTable(), die Arbeitsblattdaten automatisch in eine strukturierte DataTable konvertiert und dabei Spaltenüberschriften und Datentypen beibehält.

Schritt 1. Notwendigen Namespace importieren

Fügen Sie den Spire.XLS-Namespace hinzu, um auf wesentliche Klassen zuzugreifen.

  • C#
using Spire.Xls;

Schritt 2. Ein Formular und ein Button-Klick-Ereignis erstellen

Erstellen Sie ein Formular (z. B. Form1) und fügen Sie eine Schaltfläche mit einem Ereignishandler zum Lesen der Excel-Datei hinzu.

  • C#
public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        // Der Code kommt hierher
    }
}

Schritt 3. Das Arbeitsbuch laden

Erstellen Sie innerhalb des Button-Klick-Ereignisses ein Workbook-Objekt und laden Sie die Excel-Datei.

  • C#
Workbook wb = new Workbook();
wb.LoadFromFile("C:\\Users\\Administrator\\Desktop\\Input.xlsx");

Schritt 4. Daten in DataTable exportieren

Greifen Sie über seinen Index auf ein bestimmtes Arbeitsblatt zu und exportieren Sie seine Daten mit der Methode ExportDataTable in eine DataTable.

  • C#
DataTable dataTable = wb.Worksheets[0].ExportDataTable();

Schritt 5. Daten an DataGridView binden

Angenommen, Sie haben ein DataGridView-Steuerelement in Ihrem Formular, binden Sie die DataTable an das DataGridView, um die Daten anzuzeigen.

  • C#
dataGridView1.DataSource = dataTable;

Das Folgende ist der vollständige Code zum Lesen von Daten aus einer Excel-Datei in eine DataTable und zum Anzeigen in einem Windows Forms DataGridView-Steuerelement:

  • C#
using Spire.Xls;
using System.Data;

namespace ReadExcelIntoDataTable
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            // Erstellen Sie ein Workbook-Objekt
            Workbook wb = new Workbook();

            // Laden Sie eine vorhandene Excel-Datei
            wb.LoadFromFile("C:\\Users\\Administrator\\Desktop\\Input.xlsx");

            // Holen Sie sich das erste Arbeitsblatt
            Worksheet sheet = wb.Worksheets[0];

            // Exportieren Sie Daten aus dem Arbeitsblatt in eine DataTable
            DataTable dataTable = sheet.ExportDataTable();

            // Binden Sie die DataTable an das DataGridView
            dataGridView1.DataSource = dataTable;

            // Geben Sie Ressourcen frei
            wb.Dispose();
        }
    }
}

Ergebnis:

Die Excel-Daten werden in einer MySQL-Tabelle angezeigt.

Excel-Daten in eine Datenbank einlesen

Die Integration von Excel-Daten in eine Datenbank kann die Datenverwaltung optimieren. Im Folgenden führen wir Sie durch den Prozess des Lesens einer Excel-Datei und des Imports ihres Inhalts in eine MySQL-Datenbank. Diese Methode ist ideal für die Automatisierung der Datenmigration, die Berichterstellung oder die Synchronisierung von Excel-Daten mit einer strukturierten Datenbank.

Schritt 1. MySQL-Datenbibliothek installieren

Um mit MySQL-Datenbanken in Ihren .NET-Anwendungen zu interagieren, müssen Sie die Bibliothek MySql.Data installieren. Dieses NuGet-Paket stellt die notwendigen Klassen und Methoden zur Verfügung, um eine Verbindung zu MySQL-Datenbanken herzustellen und diese zu bearbeiten.

  • C#
Install-Package MySql.Data

Schritt 2. Notwendige Namespaces importieren

Bevor Sie mit Excel-Dateien und MySQL arbeiten, müssen Sie die erforderlichen Namespaces einbinden. Spire.XLS wird für Excel-Operationen verwendet, während MySql.Data.MySqlClient die Konnektivität zu MySQL-Datenbanken ermöglicht.

  • C#
using Spire.Xls;
using MySql.Data.MySqlClient;

Schritt 3. Kopfzeilen und Daten aus Excel extrahieren

Der folgende Codeausschnitt zeigt, wie Kopfzeilen und Daten aus der Excel-Datei extrahiert werden. Die Kopfzeilen werden bereinigt, um Konflikte bei der Benennung von MySQL-Spalten zu vermeiden, während die Daten in einem strukturierten Format für das spätere Einfügen gespeichert werden.

  • C#
// Erstellen Sie ein Workbook-Objekt
Workbook wb = new Workbook();

// Laden Sie ein Excel-Dokument
wb.LoadFromFile("C:\\Users\\Administrator\\Desktop\\Input.xlsx");

// Holen Sie sich ein bestimmtes Blatt
Worksheet sheet = wb.Worksheets[0];

// Rufen Sie die Kopfzeilen ab
List<string> headers = new List<string>();
for (int col = 1; col <= sheet.LastColumn; col++)
{
    string header = sheet.Range[1, col].Value?.ToString();
    // Leerzeichen entfernen, um Konflikte mit MySQL-Spaltennamen zu vermeiden
    string cleanHeader = header?.Replace(" ", "");
    headers.Add($"`{cleanHeader}`");
}

// Rufen Sie die Daten ab
List<List<string>> data = new List<List<string>>();
for (int row = 2; row <= sheet.LastRow; row++) {
    List<string> record = new List<string>();
    for (int col = 1; col <= sheet.LastColumn; col++)
    {
        record.Add(sheet.Range[row, col].Value?.ToString() ?? string.Empty);
    }
    data.Add(record);
}

Schritt 4. Mit einer MySQL-Datenbank verbinden

Eine Verbindung zur MySQL-Datenbank wird über eine Verbindungszeichenfolge hergestellt, die Serverdetails, Anmeldeinformationen und den Namen der Zieldatenbank enthält. Die using-Anweisung stellt die ordnungsgemäße Freigabe von Ressourcen sicher.

  • C#
string connectionString = "server=localhost;user=root;password=yourpassword;database=yourdatabase;";
using (MySqlConnection connection = new MySqlConnection(connectionString))
{
    connection.Open();
    // Die Verbindung ist hergestellt; führen Sie hier Datenbankoperationen durch
}

Schritt 5. Dynamisch eine Tabelle in MySQL erstellen

Dieser Schritt generiert dynamisch eine MySQL-Tabelle mit Spalten, die den Excel-Kopfzeilen entsprechen. Der Einfachheit halber werden alle Spalten als VARCHAR(255) festgelegt, aber die Datentypen können je nach Anforderungen angepasst werden.

  • C#
// Erstellen Sie eine Tabelle mit dynamischen Spalten basierend auf den Kopfzeilen
List<string> columns = new List<string>();
foreach (string header in headers)
{
    // Annahme, dass alle Kopfzeilenwerte zur Vereinfachung VARCHAR sind; passen Sie die Typen nach Bedarf an
    columns.Add($"{header} VARCHAR(255)");
}

// Erstellen Sie eine Tabelle in der Datenbank
string columnsSql = string.Join(", ", columns);
string createTableQuery = $ @"
    CREATE TABLE IF NOT EXISTS my_table (
        id INT AUTO_INCREMENT PRIMARY KEY,
        {columnsSql}
)";

// Führen Sie die Abfrage zum Erstellen der Tabelle aus
using (MySqlCommand createCommand = new MySqlCommand(createTableQuery, connection))
{
    createCommand.ExecuteNonQuery();
}

Schritt 6. Die Tabelle mit Daten füllen

Die extrahierten Excel-Daten werden mithilfe parametrisierter Abfragen in die MySQL-Tabelle eingefügt, um SQL-Injection zu verhindern. Jede Zeile aus der Excel-Datei wird einem entsprechenden Datenbankdatensatz zugeordnet.

  • C#
// Bereiten Sie die SQL-INSERT-Anweisung vor
string placeholders = string.Join(", ", new string[headers.Count].Select(h => "?"));
string insertQuery = $"INSERT INTO my_table ({string.Join(", ", headers.Select(h => h.Trim('`')))}) VALUES ({placeholders})";

// Fügen Sie Daten in die Tabelle ein
foreach (List<string> record in data)
{
    using (MySqlCommand insertCommand = new MySqlCommand(insertQuery, connection))
    {
        for (int i = 0; i < record.Count; i++)
        {
            insertCommand.Parameters.AddWithValue($" @2024\本地文件打包__20180302\Spire.Web\trunk\src\website\components\com_virtuemart\themes\default\templates\browse\includes\browse_searchparameter_form.tpl.php{i}", record[i]);
        }
        insertCommand.ExecuteNonQuery();
    }
}

Hier ist der vollständige Code zum Importieren von Daten aus einer Excel-Datei in eine MySQL-Tabelle:

  • C#
using Spire.Xls;
using MySql.Data.MySqlClient;

namespace ExcelToMySQL
{
    class Program
    {
        static void Main(string[] args)
        {
            // Erstellen Sie ein Workbook-Objekt
            Workbook wb = new Workbook();

            // Laden Sie ein Excel-Dokument
            wb.LoadFromFile("C:\\Users\\Administrator\\Desktop\\Input.xlsx");

            // Holen Sie sich ein bestimmtes Blatt
            Worksheet sheet = wb.Worksheets[0];

            // Rufen Sie die Kopfzeilen ab
            List<string> headers = new List<string>();
            for (int col = 1; col <= sheet.LastColumn; col++)
            {
                string header = sheet.Range[1, col].Value?.ToString();
                // Leerzeichen entfernen, um Konflikte mit MySQL-Spaltennamen zu vermeiden
                string cleanHeader = header?.Replace(" ", "");
                headers.Add($"`{cleanHeader}`");
            }

            // Rufen Sie die Daten ab
            List<List<string>> data = new List<List<string>>();
            for (int row = 2; row <= sheet.LastRow; row++)
            {
                List<string> record = new List<string>();
                for (int col = 1; col <= sheet.LastColumn; col++)
                {
                    record.Add(sheet.Range[row, col].Value?.ToString() ?? string.Empty);
                }
                data.Add(record);
            }

            // Stellen Sie eine Verbindung zur MySQL-Datenbank her
            string connectionString = "server=localhost;user=root;password=admin;database=excel_db;";
            using (MySqlConnection connection = new MySqlConnection(connectionString))
            {
                connection.Open();

                // Erstellen Sie eine Tabelle mit dynamischen Spalten basierend auf den Kopfzeilen
                List<string> columns = new List<string>();
                foreach (string header in headers)
                {
                    // Annahme, dass alle Kopfzeilenwerte zur Vereinfachung VARCHAR sind; passen Sie die Typen nach Bedarf an
                    columns.Add($"{header} VARCHAR(255)");
                }

                // Erstellen Sie eine Tabelle in der Datenbank
                string columnsSql = string.Join(", ", columns);
                string createTableQuery = $ @"
                    CREATE TABLE IF NOT EXISTS my_table (
                        id INT AUTO_INCREMENT PRIMARY KEY,
                        {columnsSql}
                    )";

                // Führen Sie die Abfrage zum Erstellen der Tabelle aus
                using (MySqlCommand createCommand = new MySqlCommand(createTableQuery, connection))
                {
                    createCommand.ExecuteNonQuery();
                }

                // Bereiten Sie die SQL-INSERT-Anweisung vor
                string placeholders = string.Join(", ", new string[headers.Count].Select(h => "?"));
                string insertQuery = $"INSERT INTO my_table ({string.Join(", ", headers.Select(h => h.Trim('`')))}) VALUES ({placeholders})";

                // Fügen Sie Daten in die Tabelle ein
                foreach (List<string> record in data)
                {
                    using (MySqlCommand insertCommand = new MySqlCommand(insertQuery, connection))
                    {
                        for (int i = 0; i < record.Count; i++)
                        {
                            insertCommand.Parameters.AddWithValue($" @2024\本地文件打包__20180302\Spire.Web\trunk\src\website\components\com_virtuemart\themes\default\templates\browse\includes\browse_searchparameter_form.tpl.php{i}", record[i]);
                        }
                        insertCommand.ExecuteNonQuery();
                    }
                }
            }

            Console.WriteLine("Daten erfolgreich exportiert!");
        }
    }
}

Ergebnis:

Die Excel-Daten werden in einer MySQL-Tabelle angezeigt.

Fazit

Das Lesen von Excel-Dateien in C# war noch nie einfacher, dank Bibliotheken wie Spire.XLS. Dieser Leitfaden hat Sie durch den Prozess des Ladens von Excel-Dateien, des Lesens ihrer Inhalte und sogar des Imports der Daten in eine MySQL-Datenbank geführt. Mit diesen Techniken können Sie die Datenverarbeitungsfähigkeiten Ihrer Anwendungen erheblich verbessern.

FAQs

F1: Kann ich passwortgeschützte Excel-Dateien lesen?

A: Ja, Spire.XLS unterstützt das Lesen verschlüsselter Excel-Dateien mit:

  • C#
wb.OpenPassword = "psd";
wb.LoadFromFile("file.xlsx");

F2: Wie lese ich Formelergebnisse anstelle der Formel selbst?

A: Sie haben zwei Möglichkeiten, Formelergebnisse abzurufen:

Für einzelne Zellen:

Prüfen Sie mit CellRange.HasFormula, ob eine Zelle eine Formel enthält, und rufen Sie den Wert mit CellRange.FormulaValue ab:

  • C#
CellRange cell = sheet.Range[1, 1];
if (cell.HasFormula)
{
    string result = cell.FormulaValue.ToString();
}

Für den Massenexport in eine DataTable:

Verwenden Sie Worksheet.ExportDataTable() mit computedFormulaValue: true, um berechnete Werte zu exportieren:

  • C#
DataTable data = sheet.ExportDataTable(range, exportColumnNames: true, computedFormulaValue: true);

F3: Wie kann ich Excel-Daten in eine DataTable einlesen?

A: Verwenden Sie die von Spire.XLS bereitgestellte Methode Worksheet.ExportDataTable().

F4: Wie kann ich eine Excel-Datei zeilenweise lesen?

A: Beziehen Sie sich auf den folgenden Code:

  • C#
Workbook workbook = new Workbook();
workbook.LoadFromFile("input.xlsx");
Worksheet sheet = workbook.Worksheets[0];

for (int row = 1; row <= sheet.LastRow; row++)
{
    for (int col = 1; col <= sheet.LastColumn; col++)
    {
        string cellValue = sheet.Range[row, col].Value?.ToString() ?? string.Empty;
        Console.WriteLine(cellValue);
    }
}

Holen Sie sich eine kostenlose Lizenz

Um die Funktionen von Spire.XLS für .NET ohne Evaluierungseinschränkungen vollständig zu erleben, können Sie eine kostenlose 30-Tage-Testlizenz anfordern.

Siehe auch

La lettura di file Excel in C# è un requisito comune per molte applicazioni, sia per l'analisi dei dati, la reportistica o l'integrazione di database. Sebbene sia possibile utilizzare le librerie Interop di Microsoft, esse presentano delle limitazioni (come la necessità che Excel sia installato). Esploreremo invece un approccio più efficiente utilizzando Spire.XLS, una libreria .NET che consente di leggere e scrivere file Excel senza Interop. Questo articolo tratta:

Libreria C# .NET per Leggere Excel Senza Interop

L'Interop di Excel di Microsoft richiede che Excel sia installato sulla macchina, rendendolo inadatto per le applicazioni lato server. Invece, librerie come Spire.XLS offrono una soluzione leggera e ad alte prestazioni senza dipendenze da Excel.

Perché usare Spire.XLS?

  • Nessuna Installazione di Excel Richiesta – Funziona in modo indipendente.
  • Supporta .NET Core e .NET Framework – Compatibilità multipiattaforma.
  • Leggi/Scrivi File Excel – Supporta .xls, .xlsx e .xlsm.
  • Importa in DataTable e Database – Integrazione perfetta con ADO.NET.

Installazione di Spire.XLS

Per iniziare, installa la libreria tramite il NuGet Package Manager:

Install-Package Spire.XLS

In alternativa, puoi scaricare Spire.XLS per .NET dal nostro sito ufficiale e fare riferimento manualmente al file DLL.

Come Leggere un File Excel in C#

Questa sezione dimostra come leggere un file Excel in C# utilizzando la libreria Spire.XLS. Il processo prevede il caricamento del file, l'accesso ai fogli di lavoro e il recupero programmatico dei valori delle celle. Ciò è utile per automatizzare l'estrazione dei dati, elaborare report di Excel o integrare i dati dei fogli di calcolo nelle applicazioni.

Passaggio 1. Importa lo Spazio dei Nomi Necessario

Per utilizzare la funzionalità di Spire.XLS, è necessario importare il suo spazio dei nomi. Ciò dà accesso a classi come Workbook e Worksheet, che sono essenziali per le operazioni sui file Excel.

  • C#
using Spire.Xls;

Passaggio 2. Carica un File Excel

Per caricare un file Excel, crea un oggetto Workbook e chiama il metodo LoadFromFile. Questo legge il file in memoria, consentendo ulteriori manipolazioni.

  • C#
Workbook wb = new Workbook();
wb.LoadFromFile("input.xlsx");

Passaggio 3. Ottieni un Foglio di Lavoro Specifico

I file Excel possono contenere più fogli di lavoro. È possibile accedere a un foglio specifico indicizzando la raccolta Worksheets (in base zero). Il primo foglio si trova all'indice 0, il secondo all'1, e così via.

  • C#
Worksheet sheet = wb.Worksheets[0]; //Primo foglio

Passaggio 4. Recupera il Valore di una Cella Specifica

Per recuperare il valore di una cella, utilizzare la proprietà CellRange.Value. Specificare gli indici di riga e colonna (a partire da 1) per individuare la cella. Ciò è utile per estrarre dati strutturati come intestazioni o record individuali.

  • C#
CellRange cell = sheet.Range[1, 1]; // Riga 1, Colonna 1 (A1)
string value = cell.Value;

Di seguito è riportato un esempio completo di lettura dei dati da un intero foglio di lavoro e della loro stampa sulla console:

  • C#
using Spire.Xls;

namespace ReadExcelData
{
    class Program
    {
        static void Main(string[] args)
        {
            // Crea un oggetto Workbook
            Workbook wb = new Workbook();

            // Carica un file Excel esistente
            wb.LoadFromFile("C:\\Users\\Administrator\\Desktop\\Input.xlsx");

            // Ottieni il primo foglio di lavoro
            Worksheet sheet = wb.Worksheets[0];

            // Ottieni l'intervallo di celle contenente i dati
            CellRange locatedRange = sheet.AllocatedRange;

            // Itera attraverso le righe
            for (int i = 0; i < locatedRange.Rows.Length; i++)
            {
                // Itera attraverso le colonne
                for (int j = 0; j < locatedRange.Rows[i].ColumnCount; j++)
                {
                    // Ottieni i dati di una cella specifica
                    string cellValue = locatedRange[i + 1, j + 1].Value?.ToString() ?? "N/A";

                    // Allinea l'output con una larghezza di 22
                    Console.Write($"{cellValue,-22}");
                }
                Console.WriteLine();
            }
        }
    }
}

Risultato:

leggi file excel in c#

Leggi i Dati di Excel in una DataTable

L'esportazione dei dati di Excel in una DataTable consente un'integrazione perfetta con i controlli dell'interfaccia utente come DataGridView o l'elaborazione dei dati di backend. Spire.XLS semplifica questo processo con il suo metodo integrato ExportDataTable(), che converte automaticamente i dati del foglio di lavoro in una DataTable strutturata preservando le intestazioni delle colonne e i tipi di dati.

Passaggio 1. Importa lo Spazio dei Nomi Necessario

Includi lo spazio dei nomi Spire.XLS per accedere alle classi essenziali.

  • C#
using Spire.Xls;

Passaggio 2. Crea un Modulo e un Evento Click del Pulsante

Crea un modulo (ad es. Form1) e aggiungi un pulsante con un gestore di eventi per la lettura del file Excel.

  • C#
public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        // Il codice andrà qui
    }
}

Passaggio 3. Carica la Cartella di Lavoro

All'interno dell'evento click del pulsante, crea un oggetto Workbook e carica il file Excel.

  • C#
Workbook wb = new Workbook();
wb.LoadFromFile("C:\\Users\\Administrator\\Desktop\\Input.xlsx");

Passaggio 4. Esporta i Dati in DataTable

Accedi a un foglio di lavoro specifico tramite il suo indice ed esporta i suoi dati in una DataTable utilizzando il metodo ExportDataTable.

  • C#
DataTable dataTable = wb.Worksheets[0].ExportDataTable();

Passaggio 5. Associa i Dati a DataGridView

Supponendo di avere un controllo DataGridView sul modulo, associa la DataTable al DataGridView per visualizzare i dati.

  • C#
dataGridView1.DataSource = dataTable;

Di seguito è riportato il codice completo per leggere i dati da un file Excel in una DataTable e visualizzarli in un controllo DataGridView di Windows Forms:

  • C#
using Spire.Xls;
using System.Data;

namespace ReadExcelIntoDataTable
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            // Crea un oggetto Workbook
            Workbook wb = new Workbook();

            // Carica un file Excel esistente
            wb.LoadFromFile("C:\\Users\\Administrator\\Desktop\\Input.xlsx");

            // Ottieni il primo foglio di lavoro
            Worksheet sheet = wb.Worksheets[0];

            // Esporta i dati dal foglio di lavoro in una DataTable
            DataTable dataTable = sheet.ExportDataTable();

            // Associa la DataTable a DataGridView
            dataGridView1.DataSource = dataTable;

            // Rilascia le risorse
            wb.Dispose();
        }
    }
}

Risultato:

I dati di Excel vengono visualizzati in una tabella MySQL.

Leggi i Dati di Excel in un Database

L'integrazione dei dati di Excel con un database può semplificare la gestione dei dati. Di seguito, illustreremo il processo di lettura di un file Excel e di importazione del suo contenuto in un database MySQL. Questo metodo è ideale per automatizzare la migrazione dei dati, la creazione di report o la sincronizzazione dei dati di Excel con un database strutturato.

Passaggio 1. Installa la Libreria Dati MySQL

Per interagire con i database MySQL nelle tue applicazioni .NET, dovrai installare la libreria MySql.Data. Questo pacchetto NuGet fornisce le classi e i metodi necessari per connettersi e manipolare i database MySQL.

  • C#
Install-Package MySql.Data

Passaggio 2. Importa gli Spazi dei Nomi Necessari

Prima di lavorare con file Excel e MySQL, è necessario includere gli spazi dei nomi richiesti. Spire.XLS viene utilizzato per le operazioni su Excel, mentre MySql.Data.MySqlClient abilita la connettività al database MySQL.

  • C#
using Spire.Xls;
using MySql.Data.MySqlClient;

Passaggio 3. Estrai Intestazioni e Dati da Excel

Il seguente frammento di codice dimostra come estrarre intestazioni e dati dal file Excel. Le intestazioni vengono pulite per evitare conflitti di denominazione delle colonne MySQL, mentre i dati vengono archiviati in un formato strutturato per un inserimento successivo.

  • C#
// Crea un oggetto Workbook
Workbook wb = new Workbook();

// Carica un documento Excel
wb.LoadFromFile("C:\\Users\\Administrator\\Desktop\\Input.xlsx");

// Ottieni un foglio specifico
Worksheet sheet = wb.Worksheets[0];

// Recupera intestazioni
List<string> headers = new List<string>();
for (int col = 1; col <= sheet.LastColumn; col++)
{
    string header = sheet.Range[1, col].Value?.ToString();
    // Rimozione degli spazi per evitare conflitti con i nomi delle colonne MySQL
    string cleanHeader = header?.Replace(" ", "");
    headers.Add($"`{cleanHeader}`");
}

// Recupera dati
List<List<string>> data = new List<List<string>>();
for (int row = 2; row <= sheet.LastRow; row++) {
    List<string> record = new List<string>();
    for (int col = 1; col <= sheet.LastColumn; col++)
    {
        record.Add(sheet.Range[row, col].Value?.ToString() ?? string.Empty);
    }
    data.Add(record);
}

Passaggio 4. Connettiti a un Database MySQL

Viene stabilita una connessione al database MySQL utilizzando una stringa di connessione, che include i dettagli del server, le credenziali e il nome del database di destinazione. L'istruzione using garantisce il corretto smaltimento delle risorse.

  • C#
string connectionString = "server=localhost;user=root;password=yourpassword;database=yourdatabase;";
using (MySqlConnection connection = new MySqlConnection(connectionString))
{
    connection.Open();
    // La connessione è stabilita; eseguire qui le operazioni sul database
}

Passaggio 5. Crea Dinamicamente una Tabella in MySQL

Questo passaggio genera dinamicamente una tabella MySQL con colonne corrispondenti alle intestazioni di Excel. Per semplicità, tutte le colonne sono impostate come VARCHAR(255), ma i tipi di dati possono essere regolati in base ai requisiti.

  • C#
// Crea una tabella con colonne dinamiche basate sulle intestazioni
List<string> columns = new List<string>();
foreach (string header in headers)
{
    // Supponendo che tutti i valori di intestazione siano VARCHAR per semplicità; regolare i tipi secondo necessità
    columns.Add($"{header} VARCHAR(255)");
}

// Crea una tabella nel database
string columnsSql = string.Join(", ", columns);
string createTableQuery = $ @"
    CREATE TABLE IF NOT EXISTS my_table (
        id INT AUTO_INCREMENT PRIMARY KEY,
        {columnsSql}
)";

// Esegui la query di creazione della tabella
using (MySqlCommand createCommand = new MySqlCommand(createTableQuery, connection))
{
    createCommand.ExecuteNonQuery();
}

Passaggio 6. Popola la Tabella con i Dati

I dati Excel estratti vengono inseriti nella tabella MySQL utilizzando query con parametri per prevenire l'iniezione di SQL. Ogni riga del file Excel viene mappata a un record di database corrispondente.

  • C#
// Prepara l'istruzione SQL INSERT
string placeholders = string.Join(", ", new string[headers.Count].Select(h => "?"));
string insertQuery = $"INSERT INTO my_table ({string.Join(", ", headers.Select(h => h.Trim('`')))}) VALUES ({placeholders})";

// Inserisci i dati nella tabella
foreach (List<string> record in data)
{
    using (MySqlCommand insertCommand = new MySqlCommand(insertQuery, connection))
    {
        for (int i = 0; i < record.Count; i++)
        {
            insertCommand.Parameters.AddWithValue($" @2024\本地文件打包__20180302\Spire.Web\trunk\src\website\components\com_virtuemart\themes\default\templates\browse\includes\browse_searchparameter_form.tpl.php{i}", record[i]);
        }
        insertCommand.ExecuteNonQuery();
    }
}

Ecco il codice completo per importare i dati da un file Excel in una tabella MySQL:

  • C#
using Spire.Xls;
using MySql.Data.MySqlClient;

namespace ExcelToMySQL
{
    class Program
    {
        static void Main(string[] args)
        {
            // Crea un oggetto Workbook
            Workbook wb = new Workbook();

            // Carica un documento Excel
            wb.LoadFromFile("C:\\Users\\Administrator\\Desktop\\Input.xlsx");

            // Ottieni un foglio specifico
            Worksheet sheet = wb.Worksheets[0];

            // Recupera intestazioni
            List<string> headers = new List<string>();
            for (int col = 1; col <= sheet.LastColumn; col++)
            {
                string header = sheet.Range[1, col].Value?.ToString();
                // Rimozione degli spazi per evitare conflitti con i nomi delle colonne MySQL
                string cleanHeader = header?.Replace(" ", "");
                headers.Add($"`{cleanHeader}`");
            }

            // Recupera dati
            List<List<string>> data = new List<List<string>>();
            for (int row = 2; row <= sheet.LastRow; row++)
            {
                List<string> record = new List<string>();
                for (int col = 1; col <= sheet.LastColumn; col++)
                {
                    record.Add(sheet.Range[row, col].Value?.ToString() ?? string.Empty);
                }
                data.Add(record);
            }

            // Stabilisci una connessione al database MySQL
            string connectionString = "server=localhost;user=root;password=admin;database=excel_db;";
            using (MySqlConnection connection = new MySqlConnection(connectionString))
            {
                connection.Open();

                // Crea una tabella con colonne dinamiche basate sulle intestazioni
                List<string> columns = new List<string>();
                foreach (string header in headers)
                {
                    // Supponendo che tutti i valori di intestazione siano VARCHAR per semplicità; regolare i tipi secondo necessità
                    columns.Add($"{header} VARCHAR(255)");
                }

                // Crea una tabella nel database
                string columnsSql = string.Join(", ", columns);
                string createTableQuery = $ @"
                    CREATE TABLE IF NOT EXISTS my_table (
                        id INT AUTO_INCREMENT PRIMARY KEY,
                        {columnsSql}
                    )";

                // Esegui la query di creazione della tabella
                using (MySqlCommand createCommand = new MySqlCommand(createTableQuery, connection))
                {
                    createCommand.ExecuteNonQuery();
                }

                // Prepara l'istruzione SQL INSERT
                string placeholders = string.Join(", ", new string[headers.Count].Select(h => "?"));
                string insertQuery = $"INSERT INTO my_table ({string.Join(", ", headers.Select(h => h.Trim('`')))}) VALUES ({placeholders})";

                // Inserisci i dati nella tabella
                foreach (List<string> record in data)
                {
                    using (MySqlCommand insertCommand = new MySqlCommand(insertQuery, connection))
                    {
                        for (int i = 0; i < record.Count; i++)
                        {
                            insertCommand.Parameters.AddWithValue($" @2024\本地文件打包__20180302\Spire.Web\trunk\src\website\components\com_virtuemart\themes\default\templates\browse\includes\browse_searchparameter_form.tpl.php{i}", record[i]);
                        }
                        insertCommand.ExecuteNonQuery();
                    }
                }
            }

            Console.WriteLine("Dati esportati con successo!");
        }
    }
}

Risultato:

I dati di Excel vengono visualizzati in una tabella MySQL.

Conclusione

Leggere file Excel in C# non è mai stato così facile, grazie a librerie come Spire.XLS. Questa guida ti ha illustrato il processo di caricamento dei file Excel, la lettura del loro contenuto e persino l'importazione dei dati in un database MySQL. Con queste tecniche, puoi migliorare notevolmente le capacità di gestione dei dati delle tue applicazioni.

Domande Frequenti

D1: Posso leggere file Excel protetti da password?

R: Sì, Spire.XLS supporta la lettura di file Excel crittografati utilizzando:

  • C#
wb.OpenPassword = "psd";
wb.LoadFromFile("file.xlsx");

D2: Come posso leggere i risultati delle formule invece della formula stessa?

R: Hai due opzioni per recuperare i risultati delle formule:

Per singole celle:

Verifica se una cella contiene una formula usando CellRange.HasFormula e ottieni il valore con CellRange.FormulaValue:

  • C#
CellRange cell = sheet.Range[1, 1];
if (cell.HasFormula)
{
    string result = cell.FormulaValue.ToString();
}

Per l'esportazione di massa in DataTable:

Usa Worksheet.ExportDataTable() con computedFormulaValue: true per esportare i valori calcolati:

  • C#
DataTable data = sheet.ExportDataTable(range, exportColumnNames: true, computedFormulaValue: true);

D3: Come posso leggere i dati di Excel in una DataTable?

R: Usa il metodo Worksheet.ExportDataTable() fornito da Spire.XLS.

D4: Come posso leggere un file Excel riga per riga?

R: Fare riferimento al seguente codice:

  • C#
Workbook workbook = new Workbook();
workbook.LoadFromFile("input.xlsx");
Worksheet sheet = workbook.Worksheets[0];

for (int row = 1; row <= sheet.LastRow; row++)
{
    for (int col = 1; col <= sheet.LastColumn; col++)
    {
        string cellValue = sheet.Range[row, col].Value?.ToString() ?? string.Empty;
        Console.WriteLine(cellValue);
    }
}

Ottieni una Licenza Gratuita

Per sperimentare appieno le funzionalità di Spire.XLS per .NET senza alcuna limitazione di valutazione, puoi richiedere una licenza di prova gratuita di 30 giorni.

Vedi Anche

A digital signature is a modern alternative to signing documents manually on paper with pen. It uses an advanced mathematical technique to check the authenticity and integrity of digital documents, which guarantees that the contents in a digital document comes from the signer and has not been altered since then. Sometimes PowerPoint documents that contain confidential information may require a signature. In this article, you will learn how to programmatically add or remove digital signatures in PowerPoint using Spire.Presentation for .NET.

Install Spire.Presentation for .NET

To begin with, you need to add the DLL files included in the Spire.Presentation for.NET package as references in your .NET project. The DLL files can be either downloaded from this link or installed via NuGet.

PM> Install-Package Spire.Presentation

Add a Digital Signature to PowerPoint in C# and VB.NET

To add a digital signature, you'll need to have a valid signature certificate first. Then you can digitally sign a PowerPoint document with the certificate using Presentation.AddDigitalSignature (X509Certificate2 certificate, string comments, DateTime signTime) method. The detailed steps are as follows.

  • Create a Presentation instance.
  • Load a sample PowerPoint document using Presentation.LoadFromFile() method.
  • Initializes an instance of X509Certificate2 class with the certificate file name and password.
  • Add a digital signature to the PowerPoint document using Presentation.AddDigitalSignature (X509Certificate2 certificate, string comments, DateTime signTime) method.
  • Save result document using Presentation.SaveToFile() method.
  • C#
  • VB.NET
using Spire.Presentation;
using System;

namespace AddDigitalSignature
{
    class Program
    {
        static void Main(string[] args)
        {
            //Create a Presentation instance
            Presentation ppt = new Presentation();
			
	    //Load a PowerPoint document
            ppt.LoadFromFile("Input.pptx");

            //Add a digital signature
            ppt.AddDigitalSignature("gary.pfx", "e-iceblue", "test", DateTime.Now);

            //Save the result document
            ppt.SaveToFile("AddDigitalSignature_result.pptx", FileFormat.Pptx2010);
            System.Diagnostics.Process.Start("AddDigitalSignature_result.pptx");

            //Dispose
            ppt.Dispose();			
        }
    }
}

C#/VB.NET: Add or Remove Digital Signatures in PowerPoint

Remove All Digital Signatures from PowerPoint in C# and VB.NET

At some point you may need to remove the digital signatures from a PowerPoint document. Spire.Presentation for .NET provides the Presentation.RemoveAllDigitalSignatures() method to remove all digital signatures at once. The detailed steps are as follows:

  • Create a Presentation instance.
  • Load a sample PowerPoint document using Presentation.LoadFromFile() method.
  • Determine if the document contains digital signatures using Presentation.IsDigitallySigned property.
  • Remove all digital signatures from the document using Presentation.RemoveAllDigitalSignatures() method.
  • Save the result document using Presentation.SaveToFile() method.
  • C#
  • VB.NET
using Spire.Presentation;

namespace RemoveDigitalSignature
{
    class Program
    {
        static void Main(string[] args)
        {
            //Create a Presentation instance
            Presentation ppt = new Presentation();

            //Load a PowerPoint document 
            ppt.LoadFromFile("AddDigitalSignature.pptx");

            //Detect if the document is digitally signed
            if (ppt.IsDigitallySigned == true)
            {
                //Remove all digital signatures
                ppt.RemoveAllDigitalSignatures();
            }

            //Save the result document
            ppt.SaveToFile("RemoveDigitalSignature.pptx", FileFormat.Pptx2013);

        }
    }
}

C#/VB.NET: Add or Remove Digital Signatures in PowerPoint

Apply for a Temporary License

If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.

Tuesday, 09 September 2014 03:39

Marker Designer

Data

Name Capital Continent Area Population
Argentina Buenos Aires South America 2777815 32300003
Bolivia La Paz South America 1098575 7300000
Brazil Brasilia South America 8511196 150400000
Canada Ottawa North America 9976147 26500000
Chile Santiago South America 756943 13200000
Colombia Bagota South America 1138907 33000000
Cuba Havana North America 114524 10600000
Ecuador Quito South America 455502 10600000
El Salvador San Salvador North America 20865 5300000
Guyana Georgetown South America 214969 800000

Option

Excel Version:
downloads
  • Demo
  • Java
  • C# source
This demo shows you the usage of WorkbookDesigner.
import com.spire.data.table.DataTable;
import com.spire.xls.FileFormat;
import com.spire.xls.Workbook;
import com.spire.xls.Worksheet;

public class MarkerDesignerDemo {

    public void markerDesignerDemo(String filePath, String dataFilePath, String resultFilePath){
        Workbook data_book = new Workbook();
        data_book.loadFromFile(dataFilePath);
        DataTable table = data_book.getWorksheets().get(0).exportDataTable();

        Workbook workbook = new Workbook();
        workbook.loadFromFile(filePath);
        Worksheet sheet = workbook.getWorksheets().get(0);
        Worksheet sheet2 = workbook.getWorksheets().get(1);

        sheet.setName( "Result");
        sheet2.setName("DataSource");
        sheet2.insertDataTable(table,true,1,1);

        workbook.getMarkerDesigner().addParameter("Variable1", 1234.5678);
        workbook.getMarkerDesigner().addDataTable("Country", table);
        workbook.getMarkerDesigner().apply();

        sheet.getAllocatedRange().autoFitRows();
        sheet.getAllocatedRange().autoFitColumns();

        workbook.saveToFile(resultFilePath, FileFormat.Version2013);


    }
}
No Matter How Big or Small Your Project is,
Any technical question related to our product, contact us at support@e-iceblue.com.
Any question related to the purchase of product, contact us at sales@e-iceblue.com.
If you don't find the function you want, please request a free demo from us.
Page 7 of 29