You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Ubuntu系统下免费将Excel指定区域转为图片的技术方案求助

可行的Excel指定区域转图片方案(Linux Ubuntu环境)

Python方案:openpyxl + matplotlib + pillow

该组合可读取Excel单元格的格式信息(字体、背景色、边框),通过matplotlib手动渲染表格并导出图片,完美适配Linux环境。

  1. 安装依赖:
pip install openpyxl matplotlib pillow
  1. 代码示例(读取Sheet1的A1:C5区域并转图片):
import openpyxl
import matplotlib.pyplot as plt
from matplotlib.table import Table

# 加载Excel文件
wb = openpyxl.load_workbook("sample.xlsx")
ws = wb["Sheet1"]

# 指定转换区域(A1到C5)
start_row, end_row = 1, 5
start_col, end_col = 1, 3

# 提取单元格数据与样式
cell_data = []
cell_styles = []
for row in range(start_row, end_row+1):
    row_data = []
    row_styles = []
    for col in range(start_col, end_col+1):
        cell = ws.cell(row=row, column=col)
        row_data.append(cell.value if cell.value is not None else "")
        
        # 提取背景色
        fill = cell.fill
        bg_color = fill.start_color.index if fill.fill_type == "solid" else "#FFFFFF"
        # 提取边框状态
        border = cell.border
        borders = {
            'left': border.left.style is not None,
            'right': border.right.style is not None,
            'top': border.top.style is not None,
            'bottom': border.bottom.style is not None
        }
        row_styles.append({"bg_color": bg_color, "borders": borders})
    cell_data.append(row_data)
    cell_styles.append(row_styles)

# 创建matplotlib表格
fig, ax = plt.subplots(figsize=(8, 4))
ax.set_axis_off()
table = Table(ax, bbox=[0, 0, 1, 1])

# 填充表格内容与样式
n_rows = len(cell_data)
n_cols = len(cell_data[0])
for i in range(n_rows):
    for j in range(n_cols):
        cell = table.add_cell(i, j, 1/n_rows, 1/n_cols, text=str(cell_data[i][j]))
        # 应用背景色
        cell.set_facecolor(cell_styles[i][j]["bg_color"].replace("FF", "#"))
        # 应用边框
        cell.set_left_edge('solid' if cell_styles[i][j]["borders"]['left'] else 'none')
        cell.set_right_edge('solid' if cell_styles[i][j]["borders"]['right'] else 'none')
        cell.set_top_edge('solid' if cell_styles[i][j]["borders"]['top'] else 'none')
        cell.set_bottom_edge('solid' if cell_styles[i][j]["borders"]['bottom'] else 'none')
        # 设置文本对齐
        cell.set_text_props(ha='center', va='center')

ax.add_table(table)
plt.savefig("excel_region.png", dpi=300, bbox_inches='tight')
plt.close()

.NET方案:EPPlus + SkiaSharp

EPPlus免费版支持读取Excel格式,SkiaSharp是跨平台2D绘图库,无需依赖Office组件即可在Linux上生成高质量图片。

  1. 创建.NET Console项目,安装NuGet包:
dotnet add package EPPlus
dotnet add package SkiaSharp
dotnet add package SkiaSharp.NativeAssets.Linux
  1. 代码示例(读取Sheet1的A1:C5区域并转图片):
using OfficeOpenXml;
using SkiaSharp;

// 配置EPPlus非商业许可证
ExcelPackage.LicenseContext = LicenseContext.NonCommercial;

// 加载Excel文件
using var package = new ExcelPackage(new FileInfo("sample.xlsx"));
var worksheet = package.Workbook.Worksheets["Sheet1"];

// 指定转换区域
var startRow = 1;
var endRow = 5;
var startCol = 1;
var endCol = 3;

// 转换Excel行列尺寸为像素
float cellWidth = (float)worksheet.Column(startCol).Width * 7;
float cellHeight = (float)worksheet.Row(startRow).Height / 1.2f;
int imgWidth = (int)((endCol - startCol + 1) * cellWidth);
int imgHeight = (int)((endRow - startRow + 1) * cellHeight);

// 创建SkiaSharp画布
using var bitmap = new SKBitmap(imgWidth, imgHeight);
using var canvas = new SKCanvas(bitmap);
canvas.Clear(SKColors.White);

// 绘制每个单元格
for (int row = startRow; row <= endRow; row++)
{
    for (int col = startCol; col <= endCol; col++)
    {
        var cell = worksheet.Cells[row, col];
        var x = (col - startCol) * cellWidth;
        var y = (row - startRow) * cellHeight;

        // 绘制背景色
        if (cell.Style.Fill.PatternType == OfficeOpenXml.Style.ExcelFillStyle.Solid)
        {
            var bgColor = cell.Style.Fill.BackgroundColor.Color;
            using var paint = new SKPaint { Color = new SKColor(bgColor.R, bgColor.G, bgColor.B) };
            canvas.DrawRect(x, y, cellWidth, cellHeight, paint);
        }

        // 绘制边框
        using var borderPaint = new SKPaint { Color = SKColors.Black, Style = SKPaintStyle.Stroke };
        if (cell.Style.Border.Left.Style != OfficeOpenXml.Style.ExcelBorderStyle.None)
            canvas.DrawLine(x, y, x, y + cellHeight, borderPaint);
        if (cell.Style.Border.Right.Style != OfficeOpenXml.Style.ExcelBorderStyle.None)
            canvas.DrawLine(x + cellWidth, y, x + cellWidth, y + cellHeight, borderPaint);
        if (cell.Style.Border.Top.Style != OfficeOpenXml.Style.ExcelBorderStyle.None)
            canvas.DrawLine(x, y, x + cellWidth, y, borderPaint);
        if (cell.Style.Border.Bottom.Style != OfficeOpenXml.Style.ExcelBorderStyle.None)
            canvas.DrawLine(x, y + cellHeight, x + cellWidth, y + cellHeight, borderPaint);

        // 绘制单元格文本
        var text = cell.Text;
        if (!string.IsNullOrEmpty(text))
        {
            using var textPaint = new SKPaint
            {
                Color = SKColors.Black,
                TextSize = 12,
                IsAntialias = true,
                TextAlign = SKTextAlign.Center
            };
            var textBounds = new SKRect();
            textPaint.MeasureText(text, ref textBounds);
            canvas.DrawText(text, x + cellWidth/2, y + cellHeight/2 + textBounds.Height/2, textPaint);
        }
    }
}

// 保存图片
using var image = SKImage.FromBitmap(bitmap);
using var data = image.Encode(SKEncodedImageFormat.Png, 100);
using var stream = File.OpenWrite("excel_region.png");
data.SaveTo(stream);

HTML中转方案:pandas + weasyprint

将Excel指定区域导出为带样式的HTML,再用weasyprint渲染为图片,可较好保留Excel的基础格式(背景、边框、文本对齐)。

  1. 安装依赖:
pip install pandas openpyxl weasyprint
  1. 代码示例:
import pandas as pd
from weasyprint import HTML

# 读取Excel指定区域
df = pd.read_excel("sample.xlsx", sheet_name="Sheet1", usecols="A:C", nrows=5)

# 生成带样式的HTML
html_str = """
<html>
<head>
    <style>
        table { border-collapse: collapse; width: 100%; }
        td, th { border: 1px solid #000; padding: 8px; text-align: center; font-family: Arial; }
        th { background-color: #f2f2f2; }
    </style>
</head>
<body>
""" + df.to_html(index=False, header=True) + """
</body>
</html>
"""

# 渲染HTML为图片
HTML(string=html_str).write_png("excel_region.png", resolution=300)

说明:若需更精准的格式匹配,可通过openpyxl读取单元格样式,手动调整HTML的CSS规则(如自定义背景色、字体大小)。

Java方案:Apache POI + Apache Batik

Apache POI读取Excel数据与样式,Apache Batik将生成的SVG表格转换为图片,完全跨平台,适合Java项目。

  1. 配置Maven依赖(pom.xml):
<dependencies>
    <dependency>
        <groupId>org.apache.poi</groupId>
        <artifactId>poi</artifactId>
        <version>5.2.5</version>
    </dependency>
    <dependency>
        <groupId>org.apache.poi</groupId>
        <artifactId>poi-ooxml</artifactId>
        <version>5.2.5</version>
    </dependency>
    <dependency>
        <groupId>org.apache.xmlgraphics</groupId>
        <artifactId>batik-all</artifactId>
        <version>1.17</version>
    </dependency>
</dependencies>
  1. 代码示例:
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.batik.dom.svg.SVGDOMImplementation;
import org.apache.batik.svggen.SVGGraphics2D;
import org.w3c.dom.DOMImplementation;
import org.w3c.dom.Document;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;

public class ExcelToImage {
    public static void main(String[] args) throws Exception {
        // 加载Excel文件
        Workbook workbook = new XSSFWorkbook(new File("sample.xlsx"));
        Sheet sheet = workbook.getSheet("Sheet1");

        // 指定转换区域(POI中行/列从0开始)
        int startRow = 0;
        int endRow = 4;
        int startCol = 0;
        int endCol = 2;

        // 定义单元格像素尺寸
        int cellWidth = 100;
        int cellHeight = 30;
        int imgWidth = (endCol - startCol + 1) * cellWidth;
        int imgHeight = (endRow - startRow + 1) * cellHeight;

        // 创建SVG绘图对象
        DOMImplementation domImpl = SVGDOMImplementation.getDOMImplementation();
        String svgNS = SVGDOMImplementation.SVG_NAMESPACE_URI;
        Document document = domImpl.createDocument(svgNS, "svg", null);
        SVGGraphics2D svgGenerator = new SVGGraphics2D(document);

        // 绘制表格
        for (int rowIdx = startRow; rowIdx <= endRow; rowIdx++) {
            Row row = sheet.getRow(rowIdx);
            for (int colIdx = startCol; colIdx <= endCol; colIdx++) {
                Cell cell = row.getCell(colIdx);
                int x = (colIdx - startCol) * cellWidth;
                int y = (rowIdx - startRow) * cellHeight;

                // 绘制背景色
                CellStyle style = cell.getCellStyle();
                Color bgColor = style.getFillForegroundColorColor();
                if (bgColor != null) {
                    svgGenerator.setColor(bgColor);
                    svgGenerator.fillRect(x, y, cellWidth, cellHeight);
                }

                // 绘制边框
                svgGenerator.setColor(Color.BLACK);
                svgGenerator.drawRect(x, y, cellWidth, cellHeight);

                // 绘制文本
                String text = cell.getStringCellValue();
                svgGenerator.setColor(Color.BLACK);
                svgGenerator.setFont(new Font("Arial", Font.PLAIN, 12));
                FontMetrics metrics = svgGenerator.getFontMetrics();
                int textX = x + (cellWidth - metrics.stringWidth(text)) / 2;
                int textY = y + (cellHeight + metrics.getAscent()) / 2;
                svgGenerator.drawString(text, textX, textY);
            }
        }

        // 将SVG转换为PNG
        BufferedImage image = new BufferedImage(imgWidth, imgHeight, BufferedImage.TYPE_INT_RGB);
        Graphics2D g2d = image.createGraphics();
        svgGenerator.getRoot().setAttribute("width", String.valueOf(imgWidth));
        svgGenerator.getRoot().setAttribute("height", String.valueOf(imgHeight));
        svgGenerator.draw(g2d);
        ImageIO.write(image, "PNG", new File("excel_region.png"));

        workbook.close();
    }
}

内容的提问来源于stack exchange,提问作者Coder Dotnet

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 07:55:21