Create and Save Excel Files through Streams with JavaScript in React
Operating Excel files as streams in web applications allows developers to dynamically create, load, modify, and save Excel files, enabling flexible and efficient data processing. Spire.XLS for JavaScript runs entirely in the browser via WebAssembly, using a virtual file system (VFS) to manage input and output files — no backend server is required. It provides a simple, easy-to-use Stream API that makes creating and saving Excel files through streams more convenient.
Working with streams greatly reduces direct disk I/O operations, improving application performance and responsiveness, especially in scenarios that involve real-time data processing or limited storage. With Spire.XLS for JavaScript, you can dynamically create an Excel file and save it to a stream, load and read workbook data from a stream, or modify content in a stream and save it as a new Excel file — all directly in the browser, simplifying data exchange and system integration.
This article covers three core features:
- Dynamically Create an Excel File and Save It to a Stream
- Load and Read an Excel File from a Stream
- Modify and Save an Excel File in a Stream
For installation and project setup, refer to Integrating Spire.XLS for JavaScript in a React Project. The examples below assume Spire.XLS is installed and the WebAssembly module is initialized.
Dynamically Create an Excel File and Save It to a Stream
With Spire.XLS for JavaScript, you can dynamically create an Excel file in the browser, fill it with data and formatting, and then save the workbook to a file stream via the SaveToStream() method. This approach eliminates the need to store files directly on disk while improving application performance and responsiveness. The steps are as follows:
- Create a
Workbookinstance to generate a new Excel workbook, clear the default worksheets, and add a new worksheet. - Access a specific worksheet using the
Worksheets.get()method. - Define the data to write to the worksheet, for example, organizing data with a two-dimensional array.
- Use the
Range.get_Item()method to access cells and set their values one by one. - Format the worksheet cells, such as setting colors, fonts, borders, or adjusting column widths.
- Create a
Streamobject and save the workbook to the file stream using theSaveToStream()method. The saved stream can be used for further processing, such as downloading as a file or transferring over the network.
Below is a complete code example demonstrating how to dynamically create an Excel file and save it to a stream in React:
function App() {
const createAndSaveToStream = async () => {
// Get the Spire.XLS WASM module
const xlsModule = window.wasmModule?.spirexls;
// Check if the module is ready
if (!xlsModule) {
alert('Spire.Xls is not ready yet');
return;
}
// Load the font file to ensure proper text rendering
await window.spire.FetchFileToVFS('ARIAL.TTF', '/Library/Fonts/', `${process.env.PUBLIC_URL}font/`);
// Create a new workbook instance
const workbook = new xlsModule.Workbook();
// Clear the default worksheets and add a new worksheet
workbook.Worksheets.Clear();
const sheet = workbook.Worksheets.Add('Data');
// Define the sample data to write to the worksheet (two-dimensional array)
const headers = ['ID', 'Name', 'Age', 'Country', 'Salary (¥)'];
const data = [
[1, 'Zhang Wei', 29, 'China', 8000],
[2, 'Li Na', 35, 'China', 12000],
[3, 'Wang Qiang', 42, 'China', 15000],
[4, 'Jack', 26, 'USA', 9500],
[5, 'Chen Si', 31, 'China', 11000],
[6, 'Ishihara Yasuko', 28, 'Japan', 8800]
];
// Write the headers to the first row
for (let col = 0; col < headers.length; col++) {
sheet.Range.get_Item({ row: 1, column: col + 1 }).Text = headers[col];
}
// Write the data to the following rows
for (let row = 0; row < data.length; row++) {
for (let col = 0; col < data[row].length; col++) {
sheet.Range.get_Item({ row: row + 2, column: col + 1 }).Text = String(data[row][col]);
}
}
// Format the header row
sheet.Range.get('A1:E1').Style.Color = xlsModule.Color.get_LightSkyBlue();
sheet.Range.get('A1:E1').Style.Font.FontName = 'Arial';
sheet.Range.get('A1:E1').Style.Font.Size = 12;
sheet.Range.get('A1:E1').Style.Font.IsBold = true;
// Format the data rows
for (let i = 2; i <= data.length + 1; i++) {
const dataRange = sheet.Range.get({
row: i, column: 1,
lastRow: i, lastColumn: headers.length
});
dataRange.Style.Color = xlsModule.Color.get_LightGray();
dataRange.Style.Font.FontName = 'Arial';
dataRange.Style.Font.Size = 11;
}
// Add borders to the header and all data cells
const usedRange = sheet.Range.get({
row: 1, column: 1,
lastRow: data.length + 1,
lastColumn: headers.length
});
usedRange.Borders.LineStyle = xlsModule.LineStyleType.Thin;
usedRange.Borders.Color = xlsModule.Color.get_LightSteelBlue();
// Adjust column widths to fit the content
for (let col = 1; col <= headers.length; col++) {
sheet.AutoFitColumn(col);
}
// Create a stream and save the workbook to it
const outputFileName = 'CreateExcelToStream.xlsx';
const fileStream = new xlsModule.Stream(outputFileName);
workbook.SaveToStream(fileStream, xlsModule.FileFormat.Version2010);
// Dispose of the workbook object to release resources
workbook.Dispose();
// Read the file from VFS and trigger download
const fileArray = window.dotnetRuntime.Module.FS.readFile(outputFileName);
const blob = new Blob([fileArray], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = outputFileName;
a.click();
URL.revokeObjectURL(url);
};
return (
<div style={{ textAlign: 'center', height: '300px' }}>
<h1>Create Excel and Save to Stream</h1>
<button onClick={createAndSaveToStream}>
Generate
</button>
</div>
);
}
export default App;
Excel file dynamically created and saved to a stream with Spire.XLS for JavaScript

Load and Read an Excel File from a Stream
With Spire.XLS for JavaScript, you can load an Excel file directly from a stream using the LoadFromStream() method. Once loaded, the cell data of the Excel file in the stream can be easily read, enabling fast and flexible data processing without file I/O operations. The steps are as follows:
- Create a
Streamobject pointing to the Excel file to be loaded. - Create a
Workbookobject and load the file from the stream using theLoadFromStream()method. - Get the first worksheet using the
Worksheets.get()method. - Iterate through the rows and columns of the worksheet and extract cell data using the
Range.get()method. - Display the extracted data on the page, or use it for other operations.
Below is a complete code example demonstrating how to load and read an Excel file from a stream in React:
import React, { useState } from 'react';
function App() {
const [extractedData, setExtractedData] = useState('');
const loadAndReadFromStream = async () => {
// Get the Spire.XLS WASM module
const xlsModule = window.wasmModule?.spirexls;
// Check if the module is ready
if (!xlsModule) {
alert('Spire.Xls is not ready yet');
return;
}
// Load the font file to ensure proper text rendering
await window.spire.FetchFileToVFS('ARIAL.TTF', '/Library/Fonts/', `${process.env.PUBLIC_URL}font/`);
// Load the sample Excel file into VFS
await window.spire.FetchFileToVFS('Sample.xlsx', '', `${process.env.PUBLIC_URL}data/`);
// Create a workbook object and load the Excel file from a stream
const workbook = new xlsModule.Workbook();
const fileStream = new xlsModule.Stream('Sample.xlsx');
workbook.LoadFromStream(fileStream, xlsModule.FileFormat.Auto);
// Get the first worksheet of the workbook
const sheet = workbook.Worksheets.get(0);
// Iterate through the rows and columns to extract cell data
const data = [];
for (let row = sheet.FirstRow; row <= sheet.LastRow; row++) {
const line = [];
for (let col = sheet.FirstColumn; col <= sheet.LastColumn; col++) {
line.push(sheet.Range.get({ row: row, column: col }).Text);
}
data.push(line.join(' | '));
}
// Dispose of the workbook object to release resources
workbook.Dispose();
// Display the extracted data on the page
setExtractedData(data.join('\n'));
};
return (
<div style={{ textAlign: 'center', height: '300px' }}>
<h1>Load and Read Excel Data from Stream</h1>
<button onClick={loadAndReadFromStream}>
Read
</button>
<pre style={{ marginTop: '20px', textAlign: 'left' }}>{extractedData}</pre>
</div>
);
}
export default App;
Excel file loaded and read from a stream with Spire.XLS for JavaScript

Modify and Save an Excel File in a Stream
With Spire.XLS for JavaScript, you can modify an Excel file in memory. First load the Excel file in the stream into a Workbook object via the LoadFromStream() method; after completing modifications such as changing cell styles or content, save the file back to a stream using the SaveToStream() method. This enables real-time changes to Excel file data without relying on direct file storage operations. The steps are as follows:
- Create a
Streamobject pointing to the Excel file and load the file from the stream via theLoadFromStream()method. - Access the worksheet using the
Worksheets.get()method. - Modify the styles of the header row and data rows (font name, size, background color, etc.) through the
CellRange.Styleproperty. - Use the
AutoFitColumn()method to automatically adjust column widths to fit the content. - Set the border style of the cells.
- Create a new
Streamobject, save the modified workbook to the stream using theSaveToStream()method, read the result file from VFS, and trigger the download.
Below is a complete code example demonstrating how to modify and save an Excel file in a stream in React:
function App() {
const modifyAndSaveInStream = async () => {
// Get the Spire.XLS WASM module
const xlsModule = window.wasmModule?.spirexls;
// Check if the module is ready
if (!xlsModule) {
alert('Spire.Xls is not ready yet');
return;
}
// Load the font file to ensure proper text rendering
await window.spire.FetchFileToVFS('ARIAL.TTF', '/Library/Fonts/', `${process.env.PUBLIC_URL}font/`);
// Load the sample Excel file into VFS
await window.spire.FetchFileToVFS('Sample.xlsx', '', `${process.env.PUBLIC_URL}data/`);
// Create a workbook object and load the Excel file from a stream
const workbook = new xlsModule.Workbook();
const fileStream = new xlsModule.Stream('Sample.xlsx');
workbook.LoadFromStream(fileStream, xlsModule.FileFormat.Auto);
// Get the first worksheet of the workbook
const sheet = workbook.Worksheets.get(0);
// Modify the style of the header row
const headerRow = sheet.Range.get({
row: sheet.FirstRow, column: sheet.FirstColumn,
lastRow: sheet.FirstRow, lastColumn: sheet.LastColumn
});
headerRow.Style.Font.FontName = 'Arial';
headerRow.Style.Font.Size = 12;
headerRow.Style.Font.IsBold = true;
headerRow.Style.Color = xlsModule.Color.get_LightSkyBlue();
// Modify the styles of the data rows, with alternating colors (even rows)
for (let i = sheet.FirstRow + 1; i <= sheet.LastRow; i++) {
const dataRow = sheet.Range.get({
row: i, column: sheet.FirstColumn,
lastRow: i, lastColumn: sheet.LastColumn
});
dataRow.Style.Font.FontName = 'Arial';
dataRow.Style.Font.Size = 10;
dataRow.Style.Color = xlsModule.Color.get_LightGray();
if (i % 2 === 0) {
dataRow.Style.Color = xlsModule.Color.get_DarkGray();
}
}
// Adjust column widths to fit the content
for (let col = sheet.FirstColumn; col <= sheet.LastColumn; col++) {
sheet.AutoFitColumn(col);
}
// Set the border color
sheet.AllocatedRange.Borders.Color = xlsModule.Color.get_White();
// Save the modified workbook to a new stream
const outputFileName = 'ModifyExcelInStream.xlsx';
const outStream = new xlsModule.Stream(outputFileName);
workbook.SaveToStream(outStream, xlsModule.FileFormat.Version2010);
// Dispose of the workbook object to release resources
workbook.Dispose();
// Read the file from VFS and trigger download
const fileArray = window.dotnetRuntime.Module.FS.readFile(outputFileName);
const blob = new Blob([fileArray], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = outputFileName;
a.click();
URL.revokeObjectURL(url);
};
return (
<div style={{ textAlign: 'center', height: '300px' }}>
<h1>Modify and Save Excel in Stream</h1>
<button onClick={modifyAndSaveInStream}>
Generate
</button>
</div>
);
}
export default App;
Excel file modified and saved in a stream with Spire.XLS for JavaScript

FAQ
How to handle the stream-saved file being unable to open in Excel?
Cause: When saving a workbook via the SaveToStream() method, if the correct output file format is not specified through the FileFormat parameter, the generated file format may not match its extension, causing it to fail to open properly.
Solution: Specify a concrete file format enum value when saving to a stream, such as xlsModule.FileFormat.Version2010:
const fileStream = new xlsModule.Stream(outputFileName);
workbook.SaveToStream(fileStream, xlsModule.FileFormat.Version2010);
How to ensure the workbook loaded from a stream correctly recognizes the file format?
Cause: The LoadFromStream() method needs to identify the file type based on the actual format of the stream data. If the format parameter is set incorrectly, loading may fail or data parsing may produce errors.
Solution: Use xlsModule.FileFormat.Auto when loading so that the library automatically detects the format of the file in the stream:
const fileStream = new xlsModule.Stream('Sample.xlsx');
workbook.LoadFromStream(fileStream, xlsModule.FileFormat.Auto);
Get a Free License
Spire.XLS for JavaScript offers a 30-day full-featured free trial license with no functional limitations. Apply here to evaluate before purchasing.
Convert Excel to Markdown or Markdown to Excel with JavaScript in React
In daily office work, data often needs to be exchanged between Excel spreadsheets and Markdown files. Markdown is a lightweight markup language widely used for documentation, blogs, and technical notes. Spire.XLS for JavaScript runs entirely in the browser via WebAssembly, using a virtual file system (VFS) to manage input and output files — no backend server is required. It provides simple, easy-to-use APIs that make format conversion more convenient.
With Spire.XLS for JavaScript, you can export Excel worksheet data as well-structured, easy-to-read Markdown tables, or import Markdown files containing table syntax to create fully formatted Excel workbooks. This makes data migration between different applications more convenient and efficient.
This article covers two core features:
For installation and project setup, refer to Integrating Spire.XLS for JavaScript in a React Project. The examples below assume Spire.XLS is installed and the WebAssembly module is initialized.
Convert Excel Workbook to Markdown File
Exporting Excel data as a Markdown table makes it convenient to read and share spreadsheet data directly in documents, blogs, or version control systems. With Spire.XLS for JavaScript, you can save an entire workbook as a Markdown file, and the resulting table is well-structured and easy to maintain. The steps are as follows:
- Create a
Workbookobject and load an existing Excel file. - Call the workbook's
SaveToFile()method, specifying the output filename and theFileFormat.Markdownfile format. - Dispose of the workbook resources, read the result file from VFS, and trigger the download.
Below is a complete code example demonstrating how to convert Excel to Markdown in React:
function App() {
const convertToMarkdown = async () => {
// Get the Spire.XLS WASM module
const xlsModule = window.wasmModule?.spirexls;
// Check if the module is ready
if (!xlsModule) {
alert('Spire.Xls is not ready yet');
return;
}
// Load the sample Excel file into VFS
await window.spire.FetchFileToVFS('Sample.xlsx', '', `${process.env.PUBLIC_URL}data/`);
// Load the font file to ensure proper text rendering
await window.spire.FetchFileToVFS('ARIAL.TTF', '/Library/Fonts/', `${process.env.PUBLIC_URL}font/`);
// Create a workbook object and load the Excel file
const workbook = new xlsModule.Workbook();
workbook.LoadFromFile({ fileName: 'Sample.xlsx' });
// Save the workbook as a Markdown file
const outputFileName = 'ExcelToMarkdown.md';
workbook.SaveToFile({ fileName: outputFileName, fileFormat: xlsModule.FileFormat.Markdown });
workbook.Dispose();
// Read the file from VFS and trigger download
const fileArray = window.dotnetRuntime.Module.FS.readFile(outputFileName);
const blob = new Blob([fileArray], { type: 'text/markdown' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = outputFileName;
a.click();
URL.revokeObjectURL(url);
};
return (
<div style={{ textAlign: 'center', height: '300px' }}>
<h1>Convert Excel to Markdown</h1>
<button onClick={convertToMarkdown}>
Generate
</button>
</div>
);
}
export default App;
Excel converted to Markdown with Spire.XLS for JavaScript

Convert Markdown File to Excel Workbook
Importing a Markdown file into an Excel spreadsheet allows you to take full advantage of Excel's formatting, calculation, and charting capabilities. Spire.XLS for JavaScript supports loading a Markdown file directly via the LoadFromMarkdown() method and converting its table data into worksheet cells. The steps are as follows:
- Load the font file and Markdown sample file into the VFS.
- Create a
Workbookobject and load the Markdown file via theLoadFromMarkdown()method. - Save the workbook as an Excel file and trigger the download.
Below is a complete code example demonstrating how to convert Markdown to Excel in React:
function App() {
const convertToExcel = async () => {
// Get the Spire.XLS WASM module
const xlsModule = window.wasmModule?.spirexls;
// Check if the module is ready
if (!xlsModule) {
alert('Spire.Xls is not ready yet');
return;
}
// Load the font file to ensure proper text rendering
await window.spire.FetchFileToVFS('ARIAL.TTF', '/Library/Fonts/', `${process.env.PUBLIC_URL}font/`);
// Load the Markdown sample file into VFS
await window.spire.FetchFileToVFS('Sample.md', '', `${process.env.PUBLIC_URL}data/`);
// Create a workbook object and load the Markdown file
const workbook = new xlsModule.Workbook();
workbook.LoadFromMarkdown('Sample.md');
// Save the workbook and release resources
const outputFileName = 'MarkdownToExcel.xlsx';
workbook.SaveToFile({ fileName: outputFileName, version: xlsModule.ExcelVersion.Version2010 });
workbook.Dispose();
// Read the file from VFS and trigger download
const fileArray = window.dotnetRuntime.Module.FS.readFile(outputFileName);
const blob = new Blob([fileArray], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = outputFileName;
a.click();
URL.revokeObjectURL(url);
};
return (
<div style={{ textAlign: 'center', height: '300px' }}>
<h1>Convert Markdown to Excel</h1>
<button onClick={convertToExcel}>
Generate
</button>
</div>
);
}
export default App;
Markdown converted to Excel with Spire.XLS for JavaScript

FAQ
How to handle font file missing issues during conversion?
Cause: If font files are not loaded into the WASM virtual file system (VFS), the exported Markdown content or imported cell text may not render correctly, especially when it contains non-ASCII characters such as Chinese.
Solution: Load the font files into VFS via FetchFileToVFS before conversion:
await window.spire.FetchFileToVFS(
'ARIAL.TTF', '/Library/Fonts/', `${process.env.PUBLIC_URL}font/`
);
How to handle the downloaded Markdown file being opened as another type or showing garbled text?
Cause: The MIME type is not set correctly when creating the Blob, so the browser cannot recognize the downloaded file as Markdown text, which may cause it to open as another type or display garbled text.
Solution: Specify the correct MIME type when downloading and make sure the download filename ends with .md:
const blob = new Blob([fileArray], { type: 'text/markdown' });
const a = document.createElement('a');
a.href = URL.createObjectURL(blob);
a.download = 'ExcelToMarkdown.md';
a.click();
Get a Free License
Spire.XLS for JavaScript offers a 30-day full-featured free trial license with no functional limitations. Apply here to evaluate before purchasing.
Add, Read, and Delete Excel Shapes with JavaScript in React
Shapes are graphic elements in Excel that enhance the visual appeal of a worksheet and convey information intuitively, such as arrows, rectangles, ovals, and stars. With shapes, you can add annotations, process-flow indicators, or decorative elements next to your data, making reports more vivid and easier to read. Spire.XLS for JavaScript runs entirely in the browser via WebAssembly, using a virtual file system (VFS) to manage input and output files — no backend server required. It provides a complete API for adding shapes and customizing their appearance (such as fill, rotation angle, text, and shadow), reading text and images from shapes, and deleting specified or all shapes.
This article covers three core features:
For installation and project setup, refer to Integrating Spire.XLS for JavaScript in a React Project. The examples below assume Spire.XLS is installed and the WebAssembly module is initialized.
Add Shapes to Excel
Adding shapes to Excel can highlight key data and beautify the layout of a worksheet. With Spire.XLS for JavaScript, you can add a shape and set its position (row, column) and size (width, height) at once using the PrstGeomShapes.AddPrstGeomShape() method, and then customize its appearance through the shape's properties — set solid, gradient, texture, or picture fill via Fill, add text via Text, set the rotation angle via Rotation, apply a shadow effect via Shadow, and control visibility via Visible. The steps are as follows:
- Create a
Workbookobject and get the default worksheet. - Add shapes using
PrstGeomShapes.AddPrstGeomShape(), setting the shape type, position, and size through the parameters. - Set solid, gradient, texture, or picture fill for the shapes via the
Fillproperty. - Add text to a shape via the
Textproperty, and set the rotation angle via theRotationproperty. - Set a shadow effect for a shape via the
Shadowproperty. - Save the workbook to an Excel file using
SaveToFile().
Below is a complete code example demonstrating how to add and customize various shapes in React:
function App() {
const addShapes = async () => {
// Get the Spire.XLS WASM module
const xlsModule = window.wasmModule?.spirexls;
// Check if the module is ready
if (!xlsModule) {
alert('Spire.Xls is not ready yet');
return;
}
// Load the picture into the virtual file system (VFS)
await window.spire.FetchFileToVFS('SpireXls.png', '', `${process.env.PUBLIC_URL}/image/`);
// Create a new workbook and get the default worksheet
const workbook = new xlsModule.Workbook();
let sheet = workbook.Worksheets.get(0);
// Add a triangle shape and fill it with a solid color
let triangle = sheet.PrstGeomShapes.AddPrstGeomShape(2, 2, 100, 100, xlsModule.PrstGeomShapeType.Triangle);
triangle.Fill.ForeColor = xlsModule.Color.get_Yellow();
triangle.Fill.FillType = xlsModule.ShapeFillType.SolidColor;
// Add text to the triangle and set its rotation angle
triangle.Text = 'Triangle';
triangle.Rotation = 45;
// Add a heart shape and fill it with a gradient color
let heart = sheet.PrstGeomShapes.AddPrstGeomShape(2, 5, 100, 100, xlsModule.PrstGeomShapeType.Heart);
heart.Fill.ForeColor = xlsModule.Color.get_Red();
heart.Fill.FillType = xlsModule.ShapeFillType.Gradient;
// Set the shadow style for the heart
heart.Shadow.Angle = 90;
heart.Shadow.Distance = 10;
heart.Shadow.Size = 150;
heart.Shadow.Color = xlsModule.Color.get_Gray();
heart.Shadow.Blur = 30;
heart.Shadow.Transparency = 1;
heart.Shadow.HasCustomStyle = true;
// Add an arrow shape
let arrow = sheet.PrstGeomShapes.AddPrstGeomShape(10, 2, 100, 100, xlsModule.PrstGeomShapeType.CurvedRightArrow);
// Add a cloud shape and fill it with a picture
let cloud = sheet.PrstGeomShapes.AddPrstGeomShape(10, 5, 100, 100, xlsModule.PrstGeomShapeType.Cloud);
cloud.Fill.CustomPicture({ im: new xlsModule.Stream('SpireXls.png'), name: 'SpireXls.png' });
// Save the workbook
const outputFileName = 'AddShapes.xlsx';
workbook.SaveToFile(outputFileName);
workbook.Dispose();
// Read the file from VFS and trigger download
const fileArray = window.dotnetRuntime.Module.FS.readFile(outputFileName);
const blob = new Blob([fileArray], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = outputFileName;
a.click();
URL.revokeObjectURL(url);
};
return (
<div style={{ textAlign: 'center', height: '300px' }}>
<h1>Add Shapes</h1>
<button onClick={addShapes}>
Generate
</button>
</div>
);
}
export default App;
Shapes added to Excel with Spire.XLS for JavaScript

Read Text and Images from Excel Shapes
Reading the text and images from shapes helps you extract the data inside shapes in batch, or reuse and archive shape resources. With Spire.XLS for JavaScript, you can load an Excel file containing shapes, get a specified shape by index via PrstGeomShapes.get(), then read its text content via the Text property and get its fill picture via Fill.Picture. The steps are as follows:
- Create a
Workbookobject and load an existing Excel file containing shapes. - Get the worksheet via
workbook.Worksheets.get(). - Get a specified shape by index using
sheet.PrstGeomShapes.get(). - Read the text in the shape via the
Textproperty. - Read the fill picture in the shape via the
Fill.Pictureproperty. - Save the read text and image as txt and png files.
Below is a complete code example demonstrating how to read text and images from shapes in React (the example loads the AddShapes.xlsx file generated in the previous section):
function App() {
const readShapes = async () => {
// Get the Spire.XLS WASM module
const xlsModule = window.wasmModule?.spirexls;
// Check if the module is ready
if (!xlsModule) {
alert('Spire.Xls is not ready yet');
return;
}
// Load the sample file containing shapes into the virtual file system (VFS)
let excelFileName = 'AddShapes.xlsx';
await window.spire.FetchFileToVFS(excelFileName, '', `${process.env.PUBLIC_URL}data/`);
// Create a workbook object and load the existing file
const workbook = new xlsModule.Workbook();
workbook.LoadFromFile({ fileName: excelFileName });
// Get the first worksheet
let sheet = workbook.Worksheets.get(0);
// Get the first shape (triangle) and read the text inside it
let triangle = sheet.PrstGeomShapes.get(0);
let text = triangle.Text;
// Get the fourth shape (cloud) and read the picture inside it
let cloud = sheet.PrstGeomShapes.get(3);
let image = cloud.Fill.Picture;
const imageFileName = 'ExtractImageFromShape.png';
image.Save(imageFileName);
workbook.Dispose();
// Save the read text to a txt file and trigger download
const textFileName = 'ExtractTextFromShape.txt';
const textBlob = new Blob([`The text in the first shape is: ${text}`], { type: 'text/plain;charset=utf-8' });
const textUrl = URL.createObjectURL(textBlob);
const a1 = document.createElement('a');
a1.href = textUrl;
a1.download = textFileName;
a1.click();
URL.revokeObjectURL(textUrl);
// Read the image file from VFS and trigger download
const fileArray = window.dotnetRuntime.Module.FS.readFile(imageFileName);
const blob = new Blob([fileArray], { type: 'application/png' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = imageFileName;
a.click();
URL.revokeObjectURL(url);
};
return (
<div style={{ textAlign: 'center', height: '300px' }}>
<h1>Read Text and Image from Shapes</h1>
<button onClick={readShapes}>
Generate
</button>
</div>
);
}
export default App;
Text and images read from Excel shapes with Spire.XLS for JavaScript

Delete Shapes in Excel
When shapes are no longer needed, deleting them in time keeps the worksheet clean and reduces the file size. With Spire.XLS for JavaScript, you can delete a specified shape via the Remove() method, or iterate through the shape collection and call Remove() on each shape to clear all shapes in a worksheet. The steps are as follows:
- Create a
Workbookobject and load an existing Excel file containing shapes. - Get the worksheet via
workbook.Worksheets.get(). - Get a specified shape using
sheet.PrstGeomShapes.get(), and call itsRemove()method to delete the shape. - Save the workbook to an Excel file using
SaveToFile().
Below is a complete code example demonstrating how to delete shapes in React (the example loads the AddShapes.xlsx file generated in the previous section):
function App() {
const deleteShapes = async () => {
// Get the Spire.XLS WASM module
const xlsModule = window.wasmModule?.spirexls;
// Check if the module is ready
if (!xlsModule) {
alert('Spire.Xls is not ready yet');
return;
}
// Load the sample file containing shapes into the virtual file system (VFS)
let excelFileName = 'AddShapes.xlsx';
await window.spire.FetchFileToVFS(excelFileName, '', `${process.env.PUBLIC_URL}data/`);
// Create a workbook object and load the existing file
const workbook = new xlsModule.Workbook();
workbook.LoadFromFile({ fileName: excelFileName });
// Get the first worksheet
let sheet = workbook.Worksheets.get(0);
// Delete the first shape in the worksheet
sheet.PrstGeomShapes.get(0).Remove();
// Delete all the shapes in the worksheet
// for (let i = sheet.PrstGeomShapes.Count - 1; i >= 0; i--) {
// sheet.PrstGeomShapes.get(i).Remove();
// }
// Save the workbook
const outputFileName = 'DeleteShapes.xlsx';
workbook.SaveToFile(outputFileName);
workbook.Dispose();
// Read the file from VFS and trigger download
const fileArray = window.dotnetRuntime.Module.FS.readFile(outputFileName);
const blob = new Blob([fileArray], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = outputFileName;
a.click();
URL.revokeObjectURL(url);
};
return (
<div style={{ textAlign: 'center', height: '300px' }}>
<h1>Delete Shapes</h1>
<button onClick={deleteShapes}>
Generate
</button>
</div>
);
}
export default App;
Specified shape deleted from Excel with Spire.XLS for JavaScript

FAQ
How to get the name and type of a shape?
Cause: When a worksheet contains many shapes, you may need to identify and locate shapes by their name or type rather than by index.
Solution: Read the Name and PrstShapeType properties of the shape to get its name and type:
// Get the worksheet
let sheet = workbook.Worksheets.get(0);
// Get the first shape
let shape = sheet.PrstGeomShapes.get(0);
// Get the name of the shape
let shapeName = shape.Name;
// Get the type of the shape
let shapeType = shape.PrstShapeType;
How to check whether a shape is currently visible?
Cause: After loading shapes from a file, you may need to determine whether a shape is hidden so that you can decide whether to process it further.
Solution: Read the Visible property of the shape to know its visibility state:
// Get the worksheet
let sheet = workbook.Worksheets.get(0);
// Get the first shape
let shape = sheet.PrstGeomShapes.get(0);
// Check whether the shape is visible
let isVisible = shape.Visible;
Get a Free License
Spire.XLS for JavaScript offers a 30-day full-featured free trial license with no functional limitations. Apply here to evaluate before purchasing.
Como inserir um hiperlink no Excel: 3 métodos fáceis

Adicionar hiperlinks no Excel é simples quando você só precisa vincular uma ou duas células. No entanto, gerenciar manualmente dezenas ou centenas de links pode se tornar demorado, especialmente ao trabalhar com arquivos externos, sites ou pastas de trabalho grandes.
Este guia explica três maneiras de adicionar um hiperlink no Excel, incluindo inserção manual, atalhos de teclado e automação baseada em Python para processamento em lote.
- Inserir um hiperlink com o recurso Link
- Inserir um hiperlink usando a função HYPERLINK
- Inserir hiperlinks em lote usando o Free Spire.XLS for Python
- Dicas para gerenciar hiperlinks no Excel
- Perguntas frequentes
Inserir um hiperlink no Excel manualmente com o recurso Link
A maneira mais direta de inserir um hiperlink no Excel é usando seu recurso integrado Link. É adequado para usuários que só precisam adicionar um pequeno número de hiperlinks manualmente. Com esse método, você pode conectar facilmente células a páginas da web externas, arquivos locais ou planilhas específicas em apenas alguns cliques.
Siga estas etapas simples para inserir hiperlinks manualmente:
- Passo 1: Selecione a célula de destino onde deseja que o link apareça.
- Passo 2: Vá para a guia Inserir na faixa de opções superior e clique em Link. Ou clique com o botão direito na célula e selecione Link no menu de contexto.

- Passo 3: Na caixa de diálogo pop-up, escolha o destino do link no painel esquerdo (por exemplo, Página da Web ou Arquivo Existente).
- Passo 4: Insira o URL da web ou o caminho do arquivo na barra de Endereço.

- Passo 5: Clique em OK para aplicar o link.
Dica: Use um atalho de teclado para inserir um hiperlink no Excel
Se você adiciona hiperlinks com frequência, pode abrir a caixa de diálogo Link diretamente com um atalho de teclado, em vez de navegar pela guia Inserir.
- No Windows, selecione a célula de destino e pressione Ctrl + K.
- No Mac, selecione a célula de destino e pressione Cmd + K.
O atalho abre a mesma caixa de diálogo Link, onde você pode inserir um URL, selecionar um arquivo local ou criar um link para outro local na pasta de trabalho. Isso fornece uma maneira rápida de inserir um hiperlink no Excel no Mac ou Windows sem abrir a guia Inserir toda vez.
Inserir um hiperlink no Excel usando a função HYPERLINK
Se você precisa criar hiperlinks a partir de dados existentes, a função HYPERLINK do Excel oferece uma alternativa conveniente à inserção manual de links. Ela permite especificar tanto o destino do link quanto o texto exibido na célula. Isso é especialmente útil quando você precisa gerar vários hiperlinks com base em URLs armazenados em uma planilha.
A sintaxe básica é
=HYPERLINK(link_location, [friendly_name])
Aqui, link_location especifica o destino do hiperlink, enquanto o friendly_name opcional determina o texto exibido na célula.
Como criar um hiperlink com a função HYPERLINK
- Passo 1: Selecione a célula onde deseja exibir o hiperlink.
- Passo 2: Insira a fórmula HYPERLINK com o URL de destino e o texto de exibição. Por exemplo:
=HYPERLINK("https://www.e-iceblue.com/","Visit Website")
- Passo 3: Pressione Enter. O Excel exibirá Visit Website como um hiperlink clicável.

- Passo 4: Se o URL e o texto de exibição estiverem armazenados em células separadas, faça referência a essas células na fórmula. Por exemplo, se o URL estiver em "A2" e o texto de exibição em "B2", insira:
=HYPERLINK(A2,B2)
- Passo 5: Arraste a fórmula para baixo para aplicá-la a outras linhas e criar vários hiperlinks automaticamente.
Essa abordagem é útil para criar listas de links, tabelas de navegação, diretórios de recursos e outros relatórios do Excel contendo muitos URLs.
Como inserir hiperlinks em lote no Excel usando o Free Spire.XLS for Python
Embora os métodos manuais e de atalho abordados acima sejam simples e convenientes, eles só são adequados para adicionar alguns hiperlinks por vez. Se você precisar processar centenas de links ou inserir uma mistura de diferentes tipos, como URLs da web, arquivos locais, endereços de e-mail e referências de planilhas internas, a entrada manual rapidamente se torna ineficiente e sujeita a erros.
Nesses casos, a automação programática pode ser uma abordagem mais eficiente. Ao utilizar o Free Spire.XLS for Python, você pode gerar e formatar dinamicamente arquivos do Excel com hiperlinks com apenas algumas linhas de código. Além disso, essa biblioteca pode automatizar a geração de hiperlinks sem exigir que o Microsoft Excel esteja instalado na máquina ou no servidor.
Passo 1: Instalar a biblioteca
Abra seu terminal ou prompt de comando e execute:
pip install Spire.Xls.Free
Passo 2: Executar o script Python
O seguinte script em Python demonstra como inserir hiperlinks em lote no Excel, incluindo links da web, endereços de e-mail, links de arquivos externos e referências de planilhas internas:
from spire.xls import *
from spire.xls.common import *
# Inicializa um novo objeto de pasta de trabalho
workbook = Workbook()
# Obtém a primeira planilha
sheet = workbook.Worksheets[0]
# Adiciona um hiperlink para um site
cell_web = sheet.Range["B3"]
url_link = sheet.HyperLinks.Add(cell_web)
url_link.Type = HyperLinkType.Url
url_link.TextToDisplay = "Visit Website"
url_link.Address = "https://www.e-iceblue.com/"
# Adiciona um hiperlink de e-mail
cell_email = sheet.Range["E3"]
mail_link = sheet.HyperLinks.Add(cell_email)
mail_link.Type = HyperLinkType.Url
mail_link.TextToDisplay = "Send Email Support"
mail_link.Address = "mailto:example@outlook.com"
# Adiciona um link para um arquivo local externo
cell_file = sheet.Range["B7"]
file_link = sheet.HyperLinks.Add(cell_file)
file_link.Type = HyperLinkType.File
file_link.TextToDisplay = "Open a local file"
file_link.Address = "/sales report.xlsx"
# Adiciona um link interno para outra planilha
cell_sheet = sheet.Range["E7"]
sheet_link = sheet.HyperLinks.Add(cell_sheet)
sheet_link.Type = HyperLinkType.Workbook
sheet_link.TextToDisplay = "Jump to Sheet2 Cell B5"
sheet_link.Address = "Sheet2!B5"
# Ajusta automaticamente as colunas para melhor apresentação
sheet.AutoFitColumn(2)
sheet.AutoFitColumn(5)
# Salva a pasta de trabalho em um arquivo Excel
workbook.SaveToFile("/output/AddHyperlinks.xlsx", ExcelVersion.Version2016)
workbook.Dispose()
Abaixo está uma prévia do arquivo Excel gerado com hiperlinks:

Por que usar Python para hiperlinks no Excel?
- Processamento em lote: Adicione vários hiperlinks em arquivos do Excel automaticamente.
- Relatórios dinâmicos: Gere demonstrações financeiras ou exportações de dados com links interativos de forma dinâmica.
Dica: Se você precisa incorporar arquivos diretamente em uma pasta de trabalho do Excel em vez de criar links clicáveis, consulte nosso guia sobre Como inserir objetos no Excel: incorporando e vinculando arquivos.
Dicas para gerenciar hiperlinks no Excel
Adicionar hiperlinks no Excel é simples, mas gerenciá-los à medida que as planilhas crescem requer alguns truques extras.
Como editar ou remover um hiperlink
- Para editar: Clique com o botão direito na célula com hiperlink e escolha Editar hiperlink para alterar o endereço de destino.
- Para remover: Clique com o botão direito na célula e clique em Remover hiperlink. O texto permanecerá, mas o link clicável será excluído.
Como criar um link para outra planilha na mesma pasta de trabalho
Para navegar na mesma planilha:
- Passo 1: Pressione Ctrl + K.
- Passo 2: Clique em Colocar neste documento no menu à esquerda.
- Passo 3: Selecione a planilha de destino na lista. Você também pode especificar uma referência de célula como
B5na parte superior. - Passo 4: Clique em OK.
Perguntas frequentes
Qual é o atalho para inserir um hiperlink no Excel para Windows e Mac?
O atalho padrão no Windows é Ctrl + K. No macOS, use Cmd + K.
Como removo vários hiperlinks no Excel de uma só vez?
Destaque todas as células que contêm hiperlinks, clique com o botão direito em qualquer lugar dentro da área selecionada e clique em Remover hiperlinks.
Posso adicionar hiperlinks a arquivos do Excel sem o Microsoft Office?
Sim. Bibliotecas Python como o Free Spire.XLS for Python permitem que você insira e modifique hiperlinks programaticamente sem ter o Microsoft Office ou o Excel instalados em sua máquina.
Conclusão
Dominar como inserir hiperlinks no Excel ajuda a criar planilhas mais interativas e organizadas. Para edições ocasionais, a inserção manual ou os atalhos de teclado geralmente são suficientes. Ao trabalhar com um grande número de links, a automação com Python oferece uma abordagem mais eficiente. Escolha o método que melhor atenda ao seu fluxo de trabalho e aos requisitos do projeto.
Leia também:
Excel에서 하이퍼링크를 삽입하는 방법: 3가지 쉬운 방법

하나 또는 두 개의 셀만 연결할 때는 엑셀에 하이퍼링크를 추가하는 것이 간단합니다. 하지만 외부 파일, 웹사이트 또는 대용량 통합 문서로 작업할 때 수십 또는 수백 개의 링크를 수동으로 관리하는 것은 상당한 시간이 소요될 수 있습니다.
본 가이드에서는 수동 삽입, 단축키, 일괄 처리를 위한 Python 기반 자동화를 포함하여 엑셀에 하이퍼링크를 추가하는 세 가지 방법을 설명합니다.
- 링크 기능을 사용하여 하이퍼링크 삽입하기
- HYPERLINK 함수를 사용하여 하이퍼링크 삽입하기
- Free Spire.XLS for Python을 사용하여 하이퍼링크 일괄 삽입하기
- 엑셀에서 하이퍼링크 관리를 위한 팁
- 자주 묻는 질문(FAQ)
링크 기능을 사용하여 엑셀에 수동으로 하이퍼링크 삽입하기
엑셀에서 하이퍼링크를 삽입하는 가장 직접적인 방법은 내장된 링크 기능을 사용하는 것입니다. 수동으로 소량의 하이퍼링크만 추가하면 되는 사용자에게 적합합니다. 이 방법을 사용하면 몇 번의 클릭만으로 셀을 외부 웹 페이지, 로컬 파일 또는 특정 워크시트에 쉽게 연결할 수 있습니다.
다음의 간단한 단계에 따라 하이퍼링크를 수동으로 삽입하세요:
- 1단계: 링크를 표시할 대상 셀을 선택합니다.
- 2단계: 상단 리본의 삽입 탭으로 이동하여 링크를 클릭합니다. 또는 셀을 마우스 오른쪽 버튼으로 클릭하고 컨텍스트 메뉴에서 링크를 선택합니다.

- 3단계: 팝업 대화 상자의 왼쪽 패널에서 링크 대상(예: 기존 파일 또는 웹 페이지)을 선택합니다.
- 4단계: 주소 표시줄에 웹 URL 또는 파일 경로를 입력합니다.

- 5단계: 확인을 클릭하여 링크를 적용합니다.
팁: 단축키를 사용하여 엑셀에 하이퍼링크 삽입하기
하이퍼링크를 자주 추가하는 경우 삽입 탭을 거치지 않고 단축키를 사용하여 링크 대화 상자를 바로 열 수 있습니다.
- Windows에서는 대상 셀을 선택하고 Ctrl + K를 누릅니다.
- Mac에서는 대상 셀을 선택하고 Cmd + K를 누릅니다.
이 단축키는 동일한 링크 대화 상자를 열어 URL을 입력하거나 로컬 파일을 선택하거나 통합 문서의 다른 위치로 링크할 수 있게 해줍니다. 이 방법을 사용하면 매번 삽입 탭을 열지 않고도 Mac 또는 Windows에서 엑셀 하이퍼링크를 빠르게 삽입할 수 있습니다.
HYPERLINK 함수를 사용하여 엑셀에 하이퍼링크 삽입하기
기존 데이터에서 하이퍼링크를 생성해야 하는 경우, 엑셀의 HYPERLINK 함수는 링크를 수동으로 삽입하는 편리한 대안을 제공합니다. 이 함수를 사용하면 링크 대상과 셀에 표시될 텍스트를 모두 지정할 수 있습니다. 특히 워크시트에 저장된 URL을 기반으로 여러 하이퍼링크를 생성해야 할 때 매우 유용합니다.
기본 구문은 다음과 같습니다.
=HYPERLINK(link_location, [friendly_name])
여기서 link_location은 하이퍼링크의 대상을 지정하고, 선택 사항인 friendly_name은 셀에 표시될 텍스트를 결정합니다.
HYPERLINK 함수로 하이퍼링크를 만드는 방법
- 1단계: 하이퍼링크를 표시할 셀을 선택합니다.
- 2단계: 대상 URL 및 표시 텍스트와 함께 HYPERLINK 수식을 입력합니다. 예:
=HYPERLINK("https://www.e-iceblue.com/","Visit Website")
- 3단계: Enter 키를 누릅니다. 엑셀에 Visit Website가 클릭 가능한 하이퍼링크로 표시됩니다.

- 4단계: URL과 표시 텍스트가 서로 다른 셀에 저장되어 있는 경우 수식에서 해당 셀을 참조합니다. 예를 들어 URL이 "A2"에 있고 표시 텍스트가 "B2"에 있는 경우 다음과 같이 입력합니다:
=HYPERLINK(A2,B2)
- 5단계: 수식을 아래로 드래그하여 다른 행에 적용하면 여러 하이퍼링크가 자동으로 생성됩니다.
이 방식은 링크 목록, 탐색 테이블, 리소스 디렉토리 및 많은 URL이 포함된 기타 엑셀 보고서를 생성하는 데 유용합니다.
Free Spire.XLS for Python을 사용하여 엑셀에 하이퍼링크를 일괄 삽입하는 방법
위에서 다룬 수동 및 단축키 방식은 간단하고 편리하지만 한 번에 몇 개의 하이퍼링크만 추가하는 경우에만 적합합니다. 수백 개의 링크를 처리해야 하거나 웹 URL, 로컬 파일, 이메일 주소, 내부 시트 참조 등 다양한 유형을 혼합하여 삽입해야 하는 경우 수동 입력은 비효율적이고 오류가 발생하기 쉽습니다.
이러한 경우에는 프로그램 방식의 자동화가 더 효율적인 접근 방식이 될 수 있습니다. Free Spire.XLS for Python을 활용하면 몇 줄의 코드만으로 하이퍼링크가 포함된 엑셀 파일을 동적으로 생성하고 서식을 지정할 수 있습니다. 또한 이 라이브러리는 컴퓨터나 서버에 Microsoft Excel이 설치되어 있지 않아도 하이퍼링크 생성을 자동화할 수 있습니다.
1단계: 라이브러리 설치
터미널 또는 명령 프롬프트를 열고 다음을 실행합니다:
pip install Spire.Xls.Free
2단계: Python 스크립트 실행
다음 Python 스크립트는 웹 링크, 이메일 주소, 외부 파일 링크 및 내부 시트 참조를 포함하여 엑셀에 하이퍼링크를 일괄 삽입하는 방법을 보여줍니다:
from spire.xls import *
from spire.xls.common import *
# 새 워크북 객체 초기화
workbook = Workbook()
# 첫 번째 워크시트 가져오기
sheet = workbook.Worksheets[0]
# 웹사이트 하이퍼링크 추가
cell_web = sheet.Range["B3"]
url_link = sheet.HyperLinks.Add(cell_web)
url_link.Type = HyperLinkType.Url
url_link.TextToDisplay = "Visit Website"
url_link.Address = "https://www.e-iceblue.com/"
# 이메일 하이퍼링크 추가
cell_email = sheet.Range["E3"]
mail_link = sheet.HyperLinks.Add(cell_email)
mail_link.Type = HyperLinkType.Url
mail_link.TextToDisplay = "Send Email Support"
mail_link.Address = "mailto:example@outlook.com"
# 외부 로컬 파일 링크 추가
cell_file = sheet.Range["B7"]
file_link = sheet.HyperLinks.Add(cell_file)
file_link.Type = HyperLinkType.File
file_link.TextToDisplay = "Open a local file"
file_link.Address = "/sales report.xlsx"
# 다른 시트로의 내부 링크 추가
cell_sheet = sheet.Range["E7"]
sheet_link = sheet.HyperLinks.Add(cell_sheet)
sheet_link.Type = HyperLinkType.Workbook
sheet_link.TextToDisplay = "Jump to Sheet2 Cell B5"
sheet_link.Address = "Sheet2!B5"
# 가독성을 위한 열 너비 자동 맞춤
sheet.AutoFitColumn(2)
sheet.AutoFitColumn(5)
# 워크북을 엑셀 파일로 저장
workbook.SaveToFile("/output/AddHyperlinks.xlsx", ExcelVersion.Version2016)
workbook.Dispose()
아래는 하이퍼링크가 생성된 엑셀 파일의 미리보기입니다:

엑셀 하이퍼링크 작업에 Python을 사용하는 이유는 무엇인가요?
- 일괄 처리: 엑셀 파일에 여러 하이퍼링크를 자동으로 추가합니다.
- 동적 보고서 작성: 대화형 링크가 포함된 재무 제표나 데이터 내보내기를 동적으로 생성합니다.
팁: 클릭 가능한 링크를 만드는 대신 엑셀 통합 문서에 파일을 직접 포함해야 하는 경우 엑셀에 개체를 삽입하는 방법: 파일 임베딩 및 연결 가이드를 참조하세요.
엑셀에서 하이퍼링크 관리를 위한 팁
엑셀에서 하이퍼링크를 추가하는 것은 간단하지만 워크시트의 규모가 커지면 하이퍼링크를 관리하는 데 몇 가지 추가 노하우가 필요합니다.
하이퍼링크를 편집하거나 제거하는 방법
- 편집하려면: 하이퍼링크가 걸린 셀을 마우스 오른쪽 버튼으로 클릭하고 하이퍼링크 편집을 선택하여 대상 주소를 변경합니다.
- 제거하려면: 셀을 마우스 오른쪽 버튼으로 클릭하고 하이퍼링크 제거를 클릭합니다. 텍스트는 남아 있지만 클릭 가능한 링크는 삭제됩니다.
동일한 통합 문서의 다른 시트로 링크하는 방법
동일한 스프레드시트 내에서 이동하려면:
- 1단계: Ctrl + K를 누릅니다.
- 2단계: 왼쪽 메뉴에서 현재 문서 참조를 클릭합니다.
- 3단계: 목록에서 대상 워크시트를 선택합니다. 상단에
B5와 같은 셀 참조를 지정할 수도 있습니다. - 4단계: 확인을 클릭합니다.
자주 묻는 질문(FAQs)
Windows 및 Mac용 엑셀에서 하이퍼링크를 삽입하는 단축키는 무엇인가요?
Windows의 기본 단축키는 Ctrl + K입니다. macOS에서는 Cmd + K를 사용하세요.
엑셀에서 여러 하이퍼링크를 한 번에 제거하려면 어떻게 해야 하나요?
하이퍼링크가 포함된 모든 셀을 선택하고 선택 영역 내부를 마우스 오른쪽 버튼으로 클릭한 후 하이퍼링크 제거를 클릭합니다.
Microsoft Office 없이도 엑셀 파일에 하이퍼링크를 추가할 수 있나요?
예, 그렇습니다. Free Spire.XLS for Python과 같은 Python 라이브러리를 사용하면 컴퓨터에 Microsoft Office나 Excel이 설치되어 있지 않아도 프로그램 방식으로 하이퍼링크를 삽입하고 수정할 수 있습니다.
결론
엑셀에서 하이퍼링크를 삽입하는 방법을 습득하면 더욱 대화형이고 체계적인 스프레드시트를 만들 수 있습니다. 가끔 수정할 때는 수동 삽입이나 단축키로도 충분합니다. 대량의 링크를 작업할 때는 Python 자동화가 더 효율적인 접근 방식을 제공합니다. 귀하의 작업 흐름과 프로젝트 요구 사항에 가장 잘 맞는 방법을 선택하세요.
함께 읽어보기:
Come inserire un collegamento ipertestuale in Excel: 3 metodi semplici
Ecco la traduzione del contenuto HTML in italiano:
Indice

Aggiungere collegamenti ipertestuali in Excel è semplice quando si devono collegare solo una o due celle. Tuttavia, la gestione manuale di decine o centinaia di collegamenti può richiedere molto tempo, specialmente quando si lavora con file esterni, siti web o cartelle di lavoro di grandi dimensioni.
Questa guida spiega tre modi per aggiungere un collegamento ipertestuale in Excel, tra cui l'inserimento manuale, le scorciatoie da tastiera e l'automazione basata su Python per l'elaborazione in serie.
- Inserire un collegamento ipertestuale con la funzione Collegamento
- Inserire un collegamento ipertestuale utilizzando la funzione HYPERLINK
- Inserire collegamenti ipertestuali in serie utilizzando Free Spire.XLS per Python
- Consigli per la gestione dei collegamenti ipertestuali in Excel
- FAQ
Inserire manualmente un collegamento ipertestuale in Excel con la funzione Collegamento
Il modo più diretto per inserire un collegamento ipertestuale in Excel è utilizzare la funzione integrata Collegamento. È adatta agli utenti che devono aggiungere solo un piccolo numero di collegamenti ipertestuali manualmente. Con questo metodo, puoi collegare facilmente le celle a pagine web esterne, file locali o fogli di lavoro specifici in pochi clic.
Segui questi semplici passaggi per inserire i collegamenti ipertestuali manualmente:
- Passaggio 1: Seleziona la cella di destinazione in cui desideri far apparire il collegamento.
- Passaggio 2: Vai alla scheda Inserisci nella barra multifunzione in alto e fai clic su Collegamento. Oppure fai clic con il pulsante destro del mouse sulla cella e seleziona Collegamento dal menu contestuale.

- Passaggio 3: Nella finestra di dialogo popup, scegli la destinazione del collegamento dal pannello di sinistra (ad es. File o pagina Web esistente).
- Passaggio 4: Inserisci l'URL del sito web o il percorso del file nella barra Indirizzo.

- Passaggio 5: Fai clic su OK per applicare il collegamento.
Suggerimento: usa una scorciatoia da tastiera per inserire un collegamento ipertestuale in Excel
Se aggiungi frequentemente collegamenti ipertestuali, puoi aprire la finestra di dialogo Collegamento direttamente con una scorciatoia da tastiera invece di navigare attraverso la scheda Inserisci.
- Su Windows, seleziona la cella di destinazione e premi Ctrl + K.
- Su Mac, seleziona la cella di destinazione e premi Cmd + K.
La scorciatoia apre la stessa finestra di dialogo Collegamento, in cui è possibile inserire un URL, selezionare un file locale o collegarsi a un'altra posizione nella cartella di lavoro. Ciò fornisce un modo rapido per inserire un collegamento ipertestuale in Excel su Mac o Windows senza aprire la scheda Inserisci ogni volta.
Inserire un collegamento ipertestuale in Excel utilizzando la funzione HYPERLINK
Se è necessario creare collegamenti ipertestuali da dati esistenti, la funzione HYPERLINK di Excel offre un'alternativa comoda all'inserimento manuale dei collegamenti. Consente di specificare sia la destinazione del collegamento sia il testo visualizzato nella cella. Questo è particolarmente utile quando è necessario generare più collegamenti ipertestuali basati su URL memorizzati in un foglio di lavoro.
La sintassi di base è
=HYPERLINK(link_location, [friendly_name])
Qui, link_location specifica la destinazione del collegamento ipertestuale, mentre l'elemento opzionale friendly_name determina il testo visualizzato nella cella.
Come creare un collegamento ipertestuale con la funzione HYPERLINK
- Passaggio 1: Seleziona la cella in cui desideri visualizzare il collegamento ipertestuale.
- Passaggio 2: Inserisci la formula HYPERLINK con l'URL di destinazione e il testo visualizzato. Ad esempio:
=HYPERLINK("https://www.e-iceblue.com/","Visita il sito web")
- Passaggio 3: Premi Invio. Excel visualizzerà Visita il sito web come collegamento ipertestuale cliccabile.

- Passaggio 4: Se l'URL e il testo visualizzato sono memorizzati in celle separate, fai riferimento a tali celle nella formula. Ad esempio, se l'URL si trova in "A2" e il testo visualizzato si trova in "B2", inserisci:
=HYPERLINK(A2,B2)
- Passaggio 5: Trascina la formula verso il basso per applicarla ad altre righe e creare automaticamente più collegamenti ipertestuali.
Questo approccio è utile per creare elenchi di collegamenti, tabelle di navigazione, directory di risorse e altri report di Excel contenenti molti URL.
Come inserire collegamenti ipertestuali in serie in Excel utilizzando Free Spire.XLS per Python
Mentre i metodi manuali e tramite scorciatoie descritti sopra sono semplici e comodi, sono adatti solo per aggiungere pochi collegamenti ipertestuali alla volta. Se è necessario elaborare centinaia di collegamenti o inserire una combinazione di tipi diversi, come URL web, file locali, indirizzi e-mail e riferimenti interni ai fogli, l'inserimento manuale diventa rapidamente inefficiente e soggetto a errori.
In questi casi, l'automazione tramite programmazione può essere un approccio più efficiente. Utilizzando Free Spire.XLS per Python, puoi generare e formattare dinamicamente file Excel con collegamenti ipertestuali con poche righe di codice. Inoltre, questa libreria può automatizzare la generazione di collegamenti ipertestuali senza richiedere l'installazione di Microsoft Excel sulla macchina o sul server.
Passaggio 1: installa la libreria
Apri il terminale o il prompt dei comandi ed esegui:
pip install Spire.Xls.Free
Passaggio 2: esegui lo script Python
Il seguente script Python mostra come inserire collegamenti ipertestuali in serie in Excel, inclusi link web, indirizzi e-mail, link a file esterni e riferimenti interni ai fogli:
from spire.xls import *
from spire.xls.common import *
# Inizializza un nuovo oggetto workbook
workbook = Workbook()
# Ottieni il primo foglio di lavoro
sheet = workbook.Worksheets[0]
# Aggiungi un collegamento ipertestuale a un sito Web
cell_web = sheet.Range["B3"]
url_link = sheet.HyperLinks.Add(cell_web)
url_link.Type = HyperLinkType.Url
url_link.TextToDisplay = "Visita il sito web"
url_link.Address = "https://www.e-iceblue.com/"
# Aggiungi un collegamento ipertestuale a un'e-mail
cell_email = sheet.Range["E3"]
mail_link = sheet.HyperLinks.Add(cell_email)
mail_link.Type = HyperLinkType.Url
mail_link.TextToDisplay = "Invia e-mail di supporto"
mail_link.Address = "mailto:example@outlook.com"
# Aggiungi un collegamento a un file locale esterno
cell_file = sheet.Range["B7"]
file_link = sheet.HyperLinks.Add(cell_file)
file_link.Type = HyperLinkType.File
file_link.TextToDisplay = "Apri un file locale"
file_link.Address = "/sales report.xlsx"
# Aggiungi un collegamento interno a un altro foglio
cell_sheet = sheet.Range["E7"]
sheet_link = sheet.HyperLinks.Add(cell_sheet)
sheet_link.Type = HyperLinkType.Workbook
sheet_link.TextToDisplay = "Passa al Foglio2 Cella B5"
sheet_link.Address = "Sheet2!B5"
# Adatta automaticamente le colonne per una presentazione migliore
sheet.AutoFitColumn(2)
sheet.AutoFitColumn(5)
# Salva la cartella di lavoro in un file Excel
workbook.SaveToFile("/output/AddHyperlinks.xlsx", ExcelVersion.Version2016)
workbook.Dispose()
Di seguito è riportata un'anteprima del file Excel generato con i collegamenti ipertestuali:

Perché usare Python per i collegamenti ipertestuali in Excel?
- Elaborazione in serie: aggiungi automaticamente più collegamenti ipertestuali nei file Excel.
- Reportistica dinamica: genera rendiconti finanziari o esportazioni di dati con collegamenti interattivi in modo dinamico.
Suggerimento: Se desideri incorporare file direttamente in una cartella di lavoro di Excel invece di creare collegamenti cliccabili, consulta la nostra guida su Come inserire oggetti in Excel: incorporare e collegare file.
Consigli per la gestione dei collegamenti ipertestuali in Excel
Aggiungere collegamenti ipertestuali in Excel è semplice, ma gestirli quando i fogli di lavoro crescono richiede alcuni trucchi aggiuntivi.
Come modificare o rimuovere un collegamento ipertestuale
- Per modificare: fai clic con il pulsante destro del mouse sulla cella contenente il collegamento e scegli Modifica collegamento ipertestuale per cambiare l'indirizzo di destinazione.
- Per rimuovere: fai clic con il pulsante destro del mouse sulla cella e fai clic su Rimuovi collegamento ipertestuale. Il testo rimarrà, ma il collegamento cliccabile verrà eliminato.
Come collegarsi a un altro foglio nella stessa cartella di lavoro
Per navigare all'interno dello stesso foglio di calcolo:
- Passaggio 1: Premi Ctrl + K.
- Passaggio 2: Fai clic su Inserisci nel documento nel menu a sinistra.
- Passaggio 3: Seleziona il foglio di lavoro di destinazione dall'elenco. Puoi anche specificare un riferimento di cella come
B5in alto. - Passaggio 4: Fai clic su OK.
FAQ
Qual è la scorciatoia per inserire un collegamento ipertestuale in Excel per Windows e Mac?
La scorciatoia predefinita su Windows è Ctrl + K. Su macOS, usa Cmd + K.
Come posso rimuovere più collegamenti ipertestuali contemporaneamente in Excel?
Evidenzia tutte le celle contenenti collegamenti ipertestuali, fai clic con il pulsante destro del mouse in un punto qualsiasi all'interno dell'area selezionata e fai clic su Rimuovi collegamenti ipertestuali.
Posso aggiungere collegamenti ipertestuali ai file Excel senza Microsoft Office?
Sì. Le librerie Python come Free Spire.XLS for Python consentono di inserire e modificare collegamenti ipertestuali a livello di programmazione senza dover installare Microsoft Office o Excel sulla macchina.
Conclusione
Padroneggiare l'inserimento di collegamenti ipertestuali in Excel aiuta a creare fogli di calcolo più interattivi e organizzati. Per modifiche occasionali, l'inserimento manuale o le scorciatoie da tastiera sono solitamente sufficienti. Quando si lavora con un gran numero di collegamenti, l'automazione in Python offre un approccio più efficiente. Scegli il metodo che meglio si adatta al tuo flusso di lavoro e ai requisiti del tuo progetto.
Leggi anche:
Comment insérer un lien hypertexte dans Excel : 3 méthodes simples
Table des matières

Ajouter des liens hypertextes dans Excel est simple lorsque vous n'avez besoin de lier qu'une ou deux cellules. Cependant, la gestion manuelle de dizaines ou de centaines de liens peut rapidement devenir très chronophage, en particulier lorsqu'il s'agit de fichiers externes, de sites Web ou de classeurs volumineux.
Ce guide explique trois façons d'ajouter un lien hypertexte dans Excel, notamment l'insertion manuelle, les raccourcis clavier et l'automatisation basée sur Python pour le traitement en lot.
- Insérer un lien hypertexte avec la fonctionnalité Lien
- Insérer un lien hypertexte à l'aide de la fonction HYPERLINK
- Insérer des liens hypertextes en lot avec Free Spire.XLS pour Python
- Conseils pour gérer les liens hypertextes dans Excel
- FAQ
Insérer manuellement un lien hypertexte dans Excel avec la fonctionnalité Lien
La façon la plus directe d'insérer un lien hypertexte dans Excel est d'utiliser sa fonctionnalité intégrée Lien. Elle convient particulièrement aux utilisateurs qui n'ont besoin d'ajouter qu'un petit nombre de liens manuellement. Grâce à cette méthode, vous pouvez facilement lier des cellules à des pages Web externes, des fichiers locaux ou des feuilles de calcul spécifiques en quelques clics.
Suivez ces étapes simples pour insérer des liens hypertextes manuellement :
- Étape 1 : Sélectionnez la cellule cible dans laquelle vous souhaitez afficher le lien.
- Étape 2 : Allez dans l'onglet Insertion du ruban supérieur et cliquez sur Lien. Vous pouvez également faire un clic droit sur la cellule et sélectionner Lien dans le menu contextuel.

- Étape 3 : Dans la boîte de dialogue contextuelle, choisissez la destination de votre lien dans le panneau de gauche (par ex. Fichier ou page Web existant).
- Étape 4 : Saisissez l'URL Web ou le chemin du fichier dans la barre Adresse.

- Étape 5 : Cliquez sur OK pour appliquer le lien.
Conseil : Utilisez un raccourci clavier pour insérer un lien hypertexte dans Excel
Si vous ajoutez fréquemment des liens hypertextes, vous pouvez ouvrir la boîte de dialogue Lien directement à l'aide d'un raccourci clavier au lieu de naviguer dans l'onglet Insertion.
- Sous Windows, sélectionnez la cellule cible et appuyez sur Ctrl + K.
- Sous Mac, sélectionnez la cellule cible et appuyez sur Cmd + K.
Le raccourci ouvre la même boîte de dialogue Lien, dans laquelle vous pouvez saisir une URL, sélectionner un fichier local ou créer un lien vers un autre emplacement du classeur. Cela vous permet d'insérer rapidement un lien hypertexte dans Excel sur Mac ou Windows sans ouvrir l'onglet Insertion à chaque fois.
Insérer un lien hypertexte dans Excel à l'aide de la fonction HYPERLINK
Si vous devez créer des liens hypertextes à partir de données existantes, la fonction HYPERLINK (LIEN_HYPERTEXTE) d'Excel offre une alternative pratique à l'insertion manuelle. Elle vous permet de spécifier à la fois la destination du lien et le texte affiché dans la cellule. Cela est particulièrement utile lorsque vous devez générer plusieurs liens hypertextes basés sur des URL stockées dans une feuille de calcul.
La syntaxe de base est la suivante :
=HYPERLINK(link_location, [friendly_name])
Ici, link_location spécifie la destination du lien hypertexte, tandis que le paramètre optionnel friendly_name détermine le texte affiché dans la cellule.
Comment créer un lien hypertexte avec la fonction HYPERLINK
- Étape 1 : Sélectionnez la cellule où vous souhaitez afficher le lien hypertexte.
- Étape 2 : Saisissez la formule HYPERLINK avec l'URL de destination et le texte d'affichage. Par exemple :
=HYPERLINK("https://www.e-iceblue.com/","Visit Website")
- Étape 3 : Appuyez sur Entrée. Excel affichera Visit Website sous forme de lien hypertexte cliquable.

- Étape 4 : Si l'URL et le texte d'affichage sont stockés dans des cellules séparées, faites référence à ces cellules dans la formule. Par exemple, si l'URL est en « A2 » et le texte d'affichage en « B2 », saisissez :
=HYPERLINK(A2,B2)
- Étape 5 : Faites glisser la formule vers le bas pour l'appliquer aux autres lignes et créer automatiquement plusieurs liens hypertextes.
Cette approche est très utile pour créer des listes de liens, des tableaux de navigation, des répertoires de ressources et d'autres rapports Excel contenant de nombreuses URL.
Comment insérer des liens hypertextes en lot dans Excel avec Free Spire.XLS pour Python
Bien que les méthodes manuelles et les raccourcis présentés ci-dessus soient simples et pratiques, ils ne conviennent qu'à l'ajout de quelques liens à la fois. Si vous devez traiter des centaines de liens ou insérer un mélange de différents types (URL Web, fichiers locaux, adresses e-mail, références de feuilles internes), la saisie manuelle devient rapidement inefficace et source d'erreurs.
Dans ce cas, l'automatisation programmatique est une approche bien plus efficace. En utilisant Free Spire.XLS pour Python, vous pouvez générer et formater dynamiquement des fichiers Excel contenant des liens hypertextes avec seulement quelques lignes de code. De plus, cette bibliothèque peut automatiser la création de liens hypertextes sans nécessiter l'installation de Microsoft Excel sur la machine ou le serveur.
Étape 1 : Installer la bibliothèque
Ouvrez votre terminal ou invite de commandes et exécutez :
pip install Spire.Xls.Free
Étape 2 : Exécuter le script Python
Le script Python suivant montre comment insérer des liens hypertextes en lot dans Excel, notamment des liens Web, des adresses e-mail, des liens vers des fichiers externes et des références internes aux feuilles :
from spire.xls import *
from spire.xls.common import *
# Initialiser un nouvel objet workbook
workbook = Workbook()
# Obtenir la première feuille de calcul
sheet = workbook.Worksheets[0]
# Ajouter un lien hypertexte vers un site Web
cell_web = sheet.Range["B3"]
url_link = sheet.HyperLinks.Add(cell_web)
url_link.Type = HyperLinkType.Url
url_link.TextToDisplay = "Visit Website"
url_link.Address = "https://www.e-iceblue.com/"
# Ajouter un lien hypertexte vers un e-mail
cell_email = sheet.Range["E3"]
mail_link = sheet.HyperLinks.Add(cell_email)
mail_link.Type = HyperLinkType.Url
mail_link.TextToDisplay = "Send Email Support"
mail_link.Address = "mailto:example@outlook.com"
# Ajouter un lien vers un fichier local externe
cell_file = sheet.Range["B7"]
file_link = sheet.HyperLinks.Add(cell_file)
file_link.Type = HyperLinkType.File
file_link.TextToDisplay = "Open a local file"
file_link.Address = "/sales report.xlsx"
# Ajouter un lien interne vers une autre feuille
cell_sheet = sheet.Range["E7"]
sheet_link = sheet.HyperLinks.Add(cell_sheet)
sheet_link.Type = HyperLinkType.Workbook
sheet_link.TextToDisplay = "Jump to Sheet2 Cell B5"
sheet_link.Address = "Sheet2!B5"
# Ajuster automatiquement la largeur des colonnes pour une meilleure présentation
sheet.AutoFitColumn(2)
sheet.AutoFitColumn(5)
# Enregistrer le classeur dans un fichier Excel
workbook.SaveToFile("/output/AddHyperlinks.xlsx", ExcelVersion.Version2016)
workbook.Dispose()
Voici un aperçu du fichier Excel généré contenant les liens hypertextes :

Pourquoi utiliser Python pour les liens hypertextes dans Excel ?
- Traitement en lot : Ajoutez automatiquement plusieurs liens hypertextes dans vos fichiers Excel.
- Rapports dynamiques : Générez de manière dynamique des états financiers ou des exportations de données intégrant des liens interactifs.
Conseil : Si vous devez intégrer directement des fichiers dans un classeur Excel au lieu de créer des liens cliquables, consultez notre guide sur Comment insérer des objets dans Excel : Intégration et liaison de fichiers.
Conseils pour gérer les liens hypertextes dans Excel
L'ajout de liens hypertextes dans Excel est simple, mais la gestion de ces liens lorsque les feuilles de calcul prennent du volume nécessite quelques astuces supplémentaires.
Comment modifier ou supprimer un lien hypertexte
- Pour modifier : Faites un clic droit sur la cellule contenant le lien hypertexte et choisissez Modifier le lien hypertexte pour changer l'adresse de destination.
- Pour supprimer : Faites un clic droit sur la cellule et cliquez sur Supprimer le lien hypertexte. Le texte restera, mais le lien cliquable sera supprimé.
Comment créer un lien vers une autre feuille dans le même classeur
Pour naviguer au sein de la même feuille de calcul :
- Étape 1 : Appuyez sur Ctrl + K.
- Étape 2 : Cliquez sur Emplacement dans ce document dans le menu de gauche.
- Étape 3 : Sélectionnez votre feuille de calcul cible dans la liste. Vous pouvez également spécifier une référence de cellule comme
B5en haut. - Étape 4 : Cliquez sur OK.
FAQ
Quel est le raccourci pour insérer un lien hypertexte dans Excel sous Windows et Mac ?
Le raccourci par défaut sous Windows est Ctrl + K. Sous macOS, utilisez Cmd + K.
Comment supprimer plusieurs liens hypertextes dans Excel en une seule fois ?
Sélectionnez toutes les cellules contenant des liens hypertextes, faites un clic droit n'importe où dans la zone sélectionnée, puis cliquez sur Supprimer les liens hypertextes.
Puis-je ajouter des liens hypertextes à des fichiers Excel sans Microsoft Office ?
Oui. Les bibliothèques Python comme Free Spire.XLS pour Python vous permettent d'insérer et de modifier des liens hypertextes par programmation sans qu'il soit nécessaire d'installer Microsoft Office ou Excel sur votre machine.
Conclusion
Maîtriser l'insertion de liens hypertextes dans Excel vous aide à créer des feuilles de calcul plus interactives et mieux organisées. Pour des modifications occasionnelles, l'insertion manuelle ou les raccourcis clavier suffisent généralement. Lors du traitement d'un grand nombre de liens, l'automatisation avec Python offre une approche plus efficace. Choisissez la méthode qui correspond le mieux à votre flux de travail et aux exigences de votre projet.
À lire aussi :
Cómo insertar un hipervínculo en Excel: 3 métodos sencillos
Tabla de contenidos

Agregar hipervínculos en Excel es sencillo cuando solo se necesita vincular una o dos celdas. Sin embargo, gestionar manualmente docenas o cientos de enlaces puede llevar mucho tiempo, especialmente cuando se trabaja con archivos externos, sitios web o libros de trabajo grandes.
Esta guía explica tres formas de agregar un hipervínculo en Excel, incluyendo la inserción manual, atajos de teclado y la automatización basada en Python para el procesamiento en lote.
- Insertar un hipervínculo con la función de enlace
- Insertar un hipervínculo utilizando la función HYPERLINK
- Insertar hipervínculos en lote usando Free Spire.XLS para Python
- Consejos para gestionar hipervínculos en Excel
- Preguntas frecuentes
Insertar un hipervínculo en Excel manualmente con la función de enlace
La forma más directa de insertar un hipervínculo en Excel es utilizando su función integrada Vínculo. Es idónea para usuarios que solo necesitan agregar una pequeña cantidad de hipervínculos manualmente. Con este método, puede conectar fácilmente celdas a páginas web externas, archivos locales o hojas de trabajo específicas en solo unos pocos clics.
Siga estos sencillos pasos para insertar hipervínculos manualmente:
- Paso 1: Seleccione la celda de destino donde desea que aparezca el enlace.
- Paso 2: Vaya a la pestaña Insertar en la cinta superior y haga clic en Vínculo. O haga clic con el botón derecho en la celda y seleccione Vínculo en el menú contextual.

- Paso 3: En el cuadro de diálogo emergente, elija el destino del enlace en el panel izquierdo (por ejemplo, Archivo o página web existente).
- Paso 4: Ingrese la URL web o la ruta del archivo en la barra Dirección.

- Paso 5: Haga clic en Aceptar para aplicar el enlace.
Consejo: Utilice un atajo de teclado para insertar un hipervínculo en Excel
Si agrega hipervínculos con frecuencia, puede abrir el cuadro de diálogo Vínculo directamente con un atajo de teclado en lugar de navegar a través de la pestaña Insertar.
- En Windows, seleccione la celda de destino y presione Ctrl + K.
- En Mac, seleccione la celda de destino y presione Cmd + K.
El atajo abre el mismo cuadro de diálogo Vínculo, donde puede ingresar una URL, seleccionar un archivo local o vincular a otra ubicación en el libro de trabajo. Esto proporciona una forma rápida de insertar un hipervínculo en Excel en Mac o Windows sin abrir la pestaña Insertar cada vez.
Insertar un hipervínculo en Excel utilizando la función HYPERLINK
Si necesita crear hipervínculos a partir de datos existentes, la función HYPERLINK (HIPERVINCULO) de Excel ofrece una alternativa conveniente a la inserción manual de enlaces. Le permite especificar tanto el destino del enlace como el texto que se muestra en la celda. Esto es especialmente útil cuando necesita generar múltiples hipervínculos basados en URL almacenadas en una hoja de trabajo.
La sintaxis básica es
=HYPERLINK(ubicacion_enlace, [nombre_descriptivo])
Aquí, ubicacion_enlace especifica el destino del hipervínculo, mientras que el parámetro opcional nombre_descriptivo determina el texto que se muestra en la celda.
Cómo crear un hipervínculo con la función HYPERLINK
- Paso 1: Seleccione la celda donde desea mostrar el hipervínculo.
- Paso 2: Ingrese la fórmula HYPERLINK con la URL de destino y el texto visible. Por ejemplo:
=HYPERLINK("https://www.e-iceblue.com/","Visitar sitio web")
- Paso 3: Presione Enter. Excel mostrará Visitar sitio web como un hipervínculo en el que se puede hacer clic.

- Paso 4: Si la URL y el texto visible están almacenados en celdas separadas, haga referencia a esas celdas en la fórmula. Por ejemplo, si la URL está en "A2" y el texto visible está en "B2", ingrese:
=HYPERLINK(A2,B2)
- Paso 5: Arrastre la fórmula hacia abajo para aplicarla a otras filas y crear múltiples hipervínculos automáticamente.
Este enfoque es útil para crear listas de enlaces, tablas de navegación, directorios de recursos y otros informes de Excel que contengan muchas URL.
Cómo insertar hipervínculos en lote en Excel usando Free Spire.XLS para Python
Si bien los métodos manuales y de atajos descritos anteriormente son sencillos y convenientes, solo son adecuados para agregar unos pocos hipervínculos a la vez. Si necesita procesar cientos de enlaces o insertar una combinación de diferentes tipos, como URL web, archivos locales, direcciones de correo electrónico y referencias a hojas internas, la entrada manual se vuelve ineficiente y propensa a errores rápidamente.
En tales casos, la automatización mediante programación puede ser un enfoque más eficiente. Al utilizar Free Spire.XLS para Python, puede generar y formatear dinámicamente archivos de Excel hipervinculados con solo unas pocas líneas de código. Además, esta biblioteca puede automatizar la generación de hipervínculos sin necesidad de tener Microsoft Excel instalado en la máquina o servidor.
Paso 1: Instalar la biblioteca
Abra su terminal o símbolo del sistema y ejecute:
pip install Spire.Xls.Free
Paso 2: Ejecutar el script de Python
El siguiente script de Python demuestra cómo insertar hipervínculos en lote en Excel, incluidos enlaces web, direcciones de correo electrónico, enlaces a archivos externos y referencias a hojas internas:
from spire.xls import *
from spire.xls.common import *
# Inicializar un nuevo objeto workbook
workbook = Workbook()
# Obtener la primera hoja de trabajo
sheet = workbook.Worksheets[0]
# Agregar un hipervínculo a un sitio web
cell_web = sheet.Range["B3"]
url_link = sheet.HyperLinks.Add(cell_web)
url_link.Type = HyperLinkType.Url
url_link.TextToDisplay = "Visitar sitio web"
url_link.Address = "https://www.e-iceblue.com/"
# Agregar un hipervínculo de correo electrónico
cell_email = sheet.Range["E3"]
mail_link = sheet.HyperLinks.Add(cell_email)
mail_link.Type = HyperLinkType.Url
mail_link.TextToDisplay = "Enviar correo de soporte"
mail_link.Address = "mailto:example@outlook.com"
# Agregar un enlace a un archivo local externo
cell_file = sheet.Range["B7"]
file_link = sheet.HyperLinks.Add(cell_file)
file_link.Type = HyperLinkType.File
file_link.TextToDisplay = "Abrir un archivo local"
file_link.Address = "/sales report.xlsx"
# Agregar un enlace interno a otra hoja
cell_sheet = sheet.Range["E7"]
sheet_link = sheet.HyperLinks.Add(cell_sheet)
sheet_link.Type = HyperLinkType.Workbook
sheet_link.TextToDisplay = "Ir a Hoja2 Celda B5"
sheet_link.Address = "Sheet2!B5"
# Autoajustar columnas para una mejor presentación
sheet.AutoFitColumn(2)
sheet.AutoFitColumn(5)
# Guardar el libro de trabajo en un archivo de Excel
workbook.SaveToFile("/output/AddHyperlinks.xlsx", ExcelVersion.Version2016)
workbook.Dispose()
A continuación se muestra una vista previa del archivo de Excel generado con hipervínculos:

¿Por qué usar Python para hipervínculos en Excel?
- Procesamiento en lote: Agregue múltiples hipervínculos en archivos de Excel automáticamente.
- Informes dinámicos: Genere estados financieros o exportaciones de datos con enlaces interactivos de forma dinámica.
Consejo: Si necesita incrustar archivos directamente en un libro de Excel en lugar de crear enlaces interactivos, consulte nuestra guía sobre Cómo insertar objetos en Excel: Incrustación y vinculación de archivos.
Consejos para gestionar hipervínculos en Excel
Agregar hipervínculos en Excel es sencillo, pero gestionarlos cuando las hojas de trabajo crecen requiere algunos trucos adicionales.
Cómo editar o eliminar un hipervínculo
- Para editar: Haga clic con el botón derecho en la celda con el hipervínculo y elija Modificar hipervínculo para cambiar la dirección de destino.
- Para eliminar: Haga clic con el botón derecho en la celda y haga clic en Quitar hipervínculo. El texto permanecerá, pero el enlace interactivo se eliminará.
Cómo vincular a otra hoja en el mismo libro de trabajo
Para navegar dentro de la misma hoja de cálculo:
- Paso 1: Presione Ctrl + K.
- Paso 2: Haga clic en Lugar de este documento en el menú izquierdo.
- Paso 3: Seleccione la hoja de trabajo de destino de la lista. También puede especificar una referencia de celda como
B5en la parte superior. - Paso 4: Haga clic en Aceptar.
Preguntas frecuentes
¿Cuál es el atajo de teclado para insertar un hipervínculo en Excel para Windows y Mac?
El atajo predeterminado en Windows es Ctrl + K. En macOS, utilice Cmd + K.
¿Cómo elimino varios hipervínculos en Excel a la vez?
Resalte todas las celdas que contienen hipervínculos, haga clic con el botón derecho en cualquier lugar del área seleccionada y haga clic en Quitar hipervínculos.
¿Puedo agregar hipervínculos a archivos de Excel sin Microsoft Office?
Sí. Las bibliotecas de Python como Free Spire.XLS para Python le permiten insertar y modificar hipervínculos mediante programación sin tener Microsoft Office o Excel instalado en su equipo.
Conclusión
Dominar cómo insertar hipervínculos en Excel le ayuda a crear hojas de cálculo más interactivas y organizadas. Para ediciones ocasionales, la inserción manual o los atajos de teclado suelen ser suficientes. Cuando trabaje con una gran cantidad de enlaces, la automatización con Python ofrece un enfoque más eficiente. Elija el método que mejor se adapte a su flujo de trabajo y a los requisitos de su proyecto.
Lea también:
So fügen Sie einen Hyperlink in Excel ein: 3 einfache Methoden

Das Hinzufügen von Hyperlinks in Excel ist einfach, wenn Sie nur eine oder zwei Zellen verknüpfen müssen. Die manuelle Verwaltung von Dutzenden oder Hunderten von Links kann jedoch zeitaufwendig werden, insbesondere beim Arbeiten mit externen Dateien, Websites oder großen Arbeitsmappen.
Dieser Leitfaden erklärt drei Möglichkeiten, um einen Hyperlink in Excel hinzuzufügen, einschließlich manueller Einfügung, Tastenkombinationen und Python-basierter Automatisierung für die Stapelverarbeitung.
- Hyperlink mit der Link-Funktion einfügen
- Hyperlink mit der HYPERLINK-Funktion einfügen
- Mehrere Hyperlinks mit Free Spire.XLS für Python einfügen
- Tipps zur Verwaltung von Hyperlinks in Excel
- FAQs
Hyperlink in Excel manuell mit der Link-Funktion einfügen
Der direkteste Weg, einen Hyperlink in Excel einzufügen, ist die Verwendung der integrierten Link-Funktion. Sie eignet sich für Benutzer, die nur eine geringe Anzahl von Hyperlinks manuell hinzufügen müssen. Mit dieser Methode können Sie Zellen mit nur wenigen Klicks ganz einfach mit externen Webseiten, lokalen Dateien oder bestimmten Arbeitsblättern verknüpfen.
Befolgen Sie diese einfachen Schritte, um Hyperlinks manuell einzufügen:
- Schritt 1: Wählen Sie die Zielzelle aus, in der der Link erscheinen soll.
- Schritt 2: Gehen Sie auf der oberen Menüleiste zur Registerkarte Einfügen und klicken Sie auf Link. Oder klicken Sie mit der rechten Maustaste auf die Zelle und wählen Sie Link aus dem Kontextmenü.

- Schritt 3: Wählen Sie im Popup-Dialogfeld auf der linken Seite Ihr Linkziel aus (z. B. Datei oder Webseite).
- Schritt 4: Geben Sie die Web-URL oder den Dateipfad in die Adresse-Zeile ein.

- Schritt 5: Klicken Sie auf OK, um den Link anzuwenden.
Tipp: Verwenden Sie eine Tastenkombination, um einen Hyperlink in Excel einzufügen
Wenn Sie häufig Hyperlinks hinzufügen, können Sie das Dialogfeld Link direkt mit einer Tastenkombination öffnen, anstatt über die Registerkarte Einfügen zu navigieren.
- Unter Windows wählen Sie die Zielzelle aus und drücken Sie Strg + K.
- Auf dem Mac wählen Sie die Zielzelle aus und drücken Sie Cmd + K.
Die Tastenkombination öffnet dasselbe Dialogfeld Link, in dem Sie eine URL eingeben, eine lokale Datei auswählen oder eine Verknüpfung zu einem anderen Ort in der Arbeitsmappe erstellen können. Dies bietet eine schnelle Möglichkeit, einen Hyperlink in Excel auf dem Mac oder unter Windows einzufügen, ohne jedes Mal die Registerkarte Einfügen öffnen zu müssen.
Hyperlink in Excel mit der HYPERLINK-Funktion einfügen
Wenn Sie Hyperlinks aus vorhandenen Daten erstellen müssen, bietet die HYPERLINK-Funktion von Excel eine praktische Alternative zum manuellen Einfügen von Links. Sie ermöglicht es Ihnen, sowohl das Linkziel als auch den in der Zelle angezeigten Text anzugeben. Dies ist besonders nützlich, wenn Sie mehrere Hyperlinks auf der Grundlage von in einem Arbeitsblatt gespeicherten URLs generieren müssen.
Die grundlegende Syntax lautet:
=HYPERLINK(link_location, [friendly_name])
Hier gibt link_location das Ziel des Hyperlinks an, während der optionale Parameter friendly_name den in der Zelle angezeigten Text bestimmt.
So erstellen Sie einen Hyperlink mit der HYPERLINK-Funktion
- Schritt 1: Wählen Sie die Zelle aus, in der der Hyperlink angezeigt werden soll.
- Schritt 2: Geben Sie die HYPERLINK-Formel mit der Ziel-URL und dem Anzeigetext ein. Zum Beispiel:
=HYPERLINK("https://www.e-iceblue.com/","Visit Website")
- Schritt 3: Drücken Sie die Eingabetaste. Excel zeigt Visit Website als klickbaren Hyperlink an.

- Schritt 4: Wenn die URL und der Anzeigetext in separaten Zellen gespeichert sind, beziehen Sie sich in der Formel auf diese Zellen. Wenn sich die URL beispielsweise in „A2“ und der Anzeigetext in „B2“ befindet, geben Sie Folgendes ein:
=HYPERLINK(A2,B2)
- Schritt 5: Ziehen Sie die Formel nach unten, um sie auf andere Zeilen anzuwenden und automatisch mehrere Hyperlinks zu erstellen.
Dieser Ansatz ist nützlich für die Erstellung von Linklisten, Navigationstabellen, Ressourcenverzeichnissen und anderen Excel-Berichten, die viele URLs enthalten.
So fügen Sie mit Free Spire.XLS für Python mehrere Hyperlinks in Excel ein
Während die oben beschriebenen manuellen Methoden und Tastenkombinationen einfach und bequem sind, eignen sie sich nur zum Hinzufügen von wenigen Hyperlinks auf einmal. Wenn Sie Hunderte von Links verarbeiten oder eine Mischung verschiedener Typen wie Web-URLs, lokale Dateien, E-Mail-Adressen und interne Arbeitsblattverweise einfügen müssen, wird die manuelle Eingabe schnell uneffizient und fehleranfällig.
In solchen Fällen kann eine programmgesteuerte Automatisierung ein effizienterer Ansatz sein. Durch die Nutzung von Free Spire.XLS für Python können Sie mit wenigen Zeilen Code dynamisch verlinkte Excel-Dateien generieren und formatieren. Darüber hinaus kann diese Bibliothek die Generierung von Hyperlinks automatisieren, ohne dass Microsoft Excel auf dem Computer oder Server installiert sein muss.
Schritt 1: Bibliothek installieren
Öffnen Sie Ihr Terminal oder Ihre Eingabeaufforderung und führen Sie Folgendes aus:
pip install Spire.Xls.Free
Schritt 2: Python-Skript ausführen
Das folgende Python-Skript demonstriert, wie Sie stapelweise Hyperlinks in Excel einfügen, einschließlich Weblinks, E-Mail-Adressen, externen Dateilinks und internen Blattreferenzen:
from spire.xls import *
from spire.xls.common import *
# Neues Arbeitsmappen-Objekt initialisieren
workbook = Workbook()
# Das erste Arbeitsblatt abrufen
sheet = workbook.Worksheets[0]
# Einen Hyperlink zu einer Website hinzufügen
cell_web = sheet.Range["B3"]
url_link = sheet.HyperLinks.Add(cell_web)
url_link.Type = HyperLinkType.Url
url_link.TextToDisplay = "Visit Website"
url_link.Address = "https://www.e-iceblue.com/"
# Einen E-Mail-Hyperlink hinzufügen
cell_email = sheet.Range["E3"]
mail_link = sheet.HyperLinks.Add(cell_email)
mail_link.Type = HyperLinkType.Url
mail_link.TextToDisplay = "Send Email Support"
mail_link.Address = "mailto:example@outlook.com"
# Einen Link zu einer externen lokalen Datei hinzufügen
cell_file = sheet.Range["B7"]
file_link = sheet.HyperLinks.Add(cell_file)
file_link.Type = HyperLinkType.File
file_link.TextToDisplay = "Open a local file"
file_link.Address = "/sales report.xlsx"
# Einen internen Link zu einem anderen Arbeitsblatt hinzufügen
cell_sheet = sheet.Range["E7"]
sheet_link = sheet.HyperLinks.Add(cell_sheet)
sheet_link.Type = HyperLinkType.Workbook
sheet_link.TextToDisplay = "Jump to Sheet2 Cell B5"
sheet_link.Address = "Sheet2!B5"
# Spaltenbreite automatisch anpassen
sheet.AutoFitColumn(2)
sheet.AutoFitColumn(5)
# Arbeitsmappe in einer Excel-Datei speichern
workbook.SaveToFile("/output/AddHyperlinks.xlsx", ExcelVersion.Version2016)
workbook.Dispose()
Unten finden Sie eine Vorschau der generierten Excel-Datei mit Hyperlinks:

Warum Python für Excel-Hyperlinks verwenden?
- Stapelverarbeitung: Fügen Sie automatisch mehrere Hyperlinks in Excel-Dateien ein.
- Dynamische Berichterstattung: Generieren Sie dynamisch Finanzberichte oder Datenexporte mit interaktiven Links.
Tipp: Wenn Sie Dateien direkt in eine Excel-Arbeitsmappe einbetten möchten, anstatt klickbare Links zu erstellen, lesen Sie unseren Leitfaden Objekte in Excel einfügen: Dateien einbetten und verknüpfen.
Tipps zur Verwaltung von Hyperlinks in Excel
Das Hinzufügen von Hyperlinks in Excel ist einfach, aber die Verwaltung bei wachsenden Arbeitsblättern erfordert ein paar zusätzliche Tricks.
So bearbeiten oder entfernen Sie einen Hyperlink
- Zum Bearbeiten: Klicken Sie mit der rechten Maustaste auf die verlinkte Zelle und wählen Sie Hyperlink bearbeiten, um die Zieladresse zu ändern.
- Zum Entfernen: Klicken Sie mit der rechten Maustaste auf die Zelle und klicken Sie auf Hyperlink entfernen. Der Text bleibt erhalten, aber der klickbare Link wird gelöscht.
So verknüpfen Sie ein anderes Arbeitsblatt in derselben Arbeitsmappe
So navigieren Sie innerhalb derselben Tabellenkalkulation:
- Schritt 1: Drücken Sie Strg + K.
- Schritt 2: Klicken Sie im linken Menü auf Aktuelles Dokument.
- Schritt 3: Wählen Sie Ihr Zielarbeitsblatt aus der Liste aus. Sie können oben auch einen Zellbezug wie
B5angeben. - Schritt 4: Klicken Sie auf OK.
FAQs
Was ist die Tastenkombination zum Einfügen eines Hyperlinks in Excel für Windows und Mac?
Die Standard-Tastenkombination unter Windows ist Strg + K. Unter macOS verwenden Sie Cmd + K.
Wie entferne ich mehrere Hyperlinks in Excel auf einmal?
Markieren Sie alle Zellen, die Hyperlinks enthalten, klicken Sie mit der rechten Maustaste auf eine beliebige Stelle im ausgewählten Bereich und klicken Sie auf Hyperlinks entfernen.
Kann ich Hyperlinks zu Excel-Dateien ohne Microsoft Office hinzufügen?
Ja. Python-Bibliotheken wie Free Spire.XLS für Python ermöglichen es Ihnen, Hyperlinks programmgesteuert einzufügen und zu ändern, ohne dass Microsoft Office oder Excel auf Ihrem Computer installiert sein muss.
Fazit
Das Beherrschen des Einfügens von Hyperlinks in Excel hilft Ihnen, interaktivere und übersichtlichere Tabellen zu erstellen. Für gelegentliche Anpassungen reichen die manuelle Einfügung oder Tastenkombinationen in der Regel aus. Bei der Arbeit mit einer großen Anzahl von Links bietet die Python-Automatisierung einen effizienteren Ansatz. Wählen Sie die Methode, die am besten zu Ihrem Arbeitsablauf und Ihren Projektanforderungen passt.
Lesen Sie auch:
Как вставить гиперссылку в Excel: 3 простых способа
Содержание

Добавление гиперссылок в Excel — простая задача, если нужно связать всего одну или две ячейки. Однако ручное управление десятками или сотнями ссылок может отнять много времени, особенно при работе с внешними файлами, веб-сайтами или большими рабочими книгами.
В этом руководстве описаны три способа добавления гиперссылки в Excel, включая ручную вставку, сочетания клавиш и автоматизацию на основе Python для пакетной обработки.
- Вставка гиперссылки с помощью функции «Ссылка»
- Вставка гиперссылки с помощью функции ГИПЕРССЫЛКА
- Пакетная вставка гиперссылок с помощью Free Spire.XLS for Python
- Советы по управлению гиперссылками в Excel
- Часто задаваемые вопросы
Ручная вставка гиперссылки в Excel с помощью функции «Ссылка»
Самый прямой способ вставить гиперссылку в Excel — использовать встроенную функцию Ссылка. Он подходит для пользователей, которым нужно вручную добавить лишь небольшое количество гиперссылок. С помощью этого метода вы можете легко связать ячейки с внешними веб-страницами, локальными файлами или конкретными листами всего за несколько кликов.
Выполните следующие простые шаги для ручной вставки гиперссылок:
- Шаг 1: Выберите целевую ячейку, в которой должна появиться ссылка.
- Шаг 2: Перейдите на вкладку Вставка на верхней ленте и нажмите Ссылка. Или щелкните ячейку правой кнопкой мыши и выберите Ссылка в контекстном меню.

- Шаг 3: В всплывающем диалоговом окне выберите назначение ссылки на левой панели (например, Файлом, веб-страницей).
- Шаг 4: Введите веб-адрес (URL) или путь к файлу в строку Адрес.

- Шаг 5: Нажмите ОК, чтобы применить ссылку.
Совет: используйте сочетание клавиш для вставки гиперссылки в Excel
Если вы часто добавляете гиперссылки, вы можете открыть диалоговое окно Ссылка напрямую с помощью сочетания клавиш, вместо того чтобы переходить через вкладку Вставка.
- В Windows выберите целевую ячейку и нажмите Ctrl + K.
- На Mac выберите целевую ячейку и нажмите Cmd + K.
Сочетание клавиш открывает то же диалоговое окно Ссылка, где вы можете ввести URL-адрес, выбрать локальный файл или сослаться на другое место в рабочей книге. Это обеспечит быстрый способ вставки гиперссылки в Excel на Mac или Windows без необходимости каждый раз открывать вкладку Вставка.
Вставка гиперссылки в Excel с помощью функции ГИПЕРССЫЛКА
Если вам нужно создать гиперссылки на основе существующих данных, функция Excel ГИПЕРССЫЛКА предоставляет удобную альтернативу ручной вставке ссылок. Она позволяет указать как назначение ссылки, так и текст, отображаемый в ячейке. Это особенно полезно, когда необходимо сгенерировать несколько гиперссылок на основе URL-адресов, сохраненных на листе.
Основной синтаксис:
=HYPERLINK(link_location, [friendly_name])
Здесь link_location указывает назначение гиперссылки, а необязательный параметр friendly_name определяет текст, отображаемый в ячейке.
Как создать гиперссылку с помощью функции ГИПЕРССЫЛКА
- Шаг 1: Выберите ячейку, в которой вы хотите отобразить гиперссылку.
- Шаг 2: Введите формулу ГИПЕРССЫЛКА с URL-адресом назначения и отображаемым текстом. Например:
=HYPERLINK("https://www.e-iceblue.com/","Visit Website")
- Шаг 3: Нажмите Enter. Excel отобразит Visit Website в виде кликабельной гиперссылки.

- Шаг 4: Если URL-адрес и отображаемый текст хранятся в разных ячейках, сошлитесь на эти ячейки в формуле. Например, если URL-адрес находится в «A2», а отображаемый текст — в «B2», введите:
=HYPERLINK(A2,B2)
- Шаг 5: Протяните формулу вниз, чтобы применить ее к другим строкам и автоматически создать несколько гиперссылок.
Этот подход полезен для создания списков ссылок, навигационных таблиц, каталогов ресурсов и других отчетов Excel, содержащих множество URL-адресов.
Пакетная вставка гиперссылок в Excel с помощью Free Spire.XLS for Python
Хотя описанные выше ручные методы и сочетания клавиш просты и удобны, они подходят только для добавления нескольких гиперссылок за раз. Если вам нужно обработать сотни ссылок или вставить комбинацию различных типов (например, веб-адреса, локальные файлы, адреса электронной почты и ссылки на внутренние листы), ручной ввод быстро становится неэффективным и приведет к ошибкам.
В таких случаях более эффективным подходом может стать программная автоматизация. Используя Free Spire.XLS for Python, вы можете динамически создавать и форматировать файлы Excel с гиперссылками с помощью нескольких строк кода. Более того, эта библиотека может автоматизировать создание гиперссылок без необходимости установки Microsoft Excel на компьютере или сервере.
Шаг 1: Установка библиотеки
Откройте терминал или командную строку и выполните:
pip install Spire.Xls.Free
Шаг 2: Запуск Python-скрипта
Следующий скрипт на Python демонстрирует, как выполняя пакетную обработку вставлять гиперссылки в Excel, включая веб-ссылки, адреса электронной почты, ссылки на внешние файлы и ссылки на внутренние листы:
from spire.xls import *
from spire.xls.common import *
# Инициализация нового объекта рабочей книги
workbook = Workbook()
# Получение первого листа
sheet = workbook.Worksheets[0]
# Добавление гиперссылки на веб-сайт
cell_web = sheet.Range["B3"]
url_link = sheet.HyperLinks.Add(cell_web)
url_link.Type = HyperLinkType.Url
url_link.TextToDisplay = "Visit Website"
url_link.Address = "https://www.e-iceblue.com/"
# Добавление гиперссылки на Email
cell_email = sheet.Range["E3"]
mail_link = sheet.HyperLinks.Add(cell_email)
mail_link.Type = HyperLinkType.Url
mail_link.TextToDisplay = "Send Email Support"
mail_link.Address = "mailto:example@outlook.com"
# Добавление ссылки на внешний локальный файл
cell_file = sheet.Range["B7"]
file_link = sheet.HyperLinks.Add(cell_file)
file_link.Type = HyperLinkType.File
file_link.TextToDisplay = "Open a local file"
file_link.Address = "/sales report.xlsx"
# Добавление внутренней ссылки на другой лист
cell_sheet = sheet.Range["E7"]
sheet_link = sheet.HyperLinks.Add(cell_sheet)
sheet_link.Type = HyperLinkType.Workbook
sheet_link.TextToDisplay = "Jump to Sheet2 Cell B5"
sheet_link.Address = "Sheet2!B5"
# Автоподбор ширины колонок для лучшего отображения
sheet.AutoFitColumn(2)
sheet.AutoFitColumn(5)
# Сохранение рабочей книги в файл Excel
workbook.SaveToFile("/output/AddHyperlinks.xlsx", ExcelVersion.Version2016)
workbook.Dispose()
Ниже представлен предпросмотр сгенерированного файла Excel с гиперссылками:

Зачем использовать Python для гиперссылок в Excel?
- Пакетная обработка: автоматическое добавление нескольких гиперссылок в файлы Excel.
- Динамическая отчетность: динамическое создание финансовых отчетов или экспорта данных с интерактивными ссылками.
Совет: Если вам нужно внедрить файлы непосредственно в рабочую книгу Excel вместо создания кликабельных ссылок, см. наше руководство Как вставить объекты в Excel: внедрение и связывание файлов.
Советы по управлению гиперссылками в Excel
Добавление гиперссылок в Excel не вызывает сложностей, но управление ими по мере роста объема рабочих листов требует нескольких дополнительных приемов.
Как изменить или удалить гиперссылку
- Для изменения: Щелкните ячейку с гиперссылкой правой кнопкой мыши и выберите Изменить гиперссылку, чтобы изменить адрес назначения.
- Для удаления: Щелкните ячейку правой кнопкой мыши и выберите Удалить гиперссылку. Текст останется, но кликабельная ссылка будет удалена.
Как сослаться на другой лист в той же рабочей книге
Чтобы настроить навигацию внутри той же электронной таблицы:
- Шаг 1: Нажмите Ctrl + K.
- Шаг 2: Выберите Местом в этом документе в левом меню.
- Шаг 3: Выберите целевой рабочий лист из списка. Вы также можете указать ссылку на ячейку, например
B5, вверху. - Шаг 4: Нажмите ОК.
Часто задаваемые вопросы
Какое сочетание клавиш используется для вставки гиперссылки в Excel для Windows и Mac?
По умолчанию в Windows используется сочетание Ctrl + K. В macOS используйте Cmd + K.
Как удалить несколько гиперссылок в Excel одновременно?
Выделите все ячейки, содержащие гиперссылки, щелкните правой кнопкой мыши в любом месте выделенной области и выберите Удалить гиперссылки.
Можно ли добавлять гиперссылки в файлы Excel без Microsoft Office?
Да. Библиотеки Python, такие как Free Spire.XLS for Python, позволяют программно вставлять и изменять гиперссылки без необходимости установки Microsoft Office или Excel на вашем компьютере.
Заключение
Освоение способов вставки гиперссылок в Excel помогает создавать более интерактивные и упорядоченные электронные таблицы. Для редких правок обычно достаточно ручного ввода или сочетаний клавиш. При работе с большим количеством ссылок автоматизация на Python обеспечивает более эффективный подход. Выберите метод, который лучше всего соответствует вашему рабочему процессу и требованиям проекта.