用Python导入CSV和Excel表格数据到Word表格

在不同格式的文档之间进行数据传输是非常重要的操作。例如将CSV和Excel表格数据导入到Word文档中,不仅可以实现数据的有效整合与展示,还能极大地提升工作效率和文档的专业性。无论是生成报告、制作统计分析还是编制业务文档,熟练掌握用Python处理这些常见文档的数据,能帮助我们更灵活地管理和呈现信息,满足各种需求。本文将介绍如何使用Python将CSV和Excel表格数据导入到Word文档中并创建表格

文章目录

本文所使用的方法需要用到Spire.Doc for Python,PyPI:pip install Spire.Doc

用Python导入CSV数据到Word表格

CSV文件中的表格数据可以使用Python标准库中的csv模块直接读取为字符串,然后我们再使用Spire.Doc for Python中的方法和属性利用读取的数据在Word文档中创建表格,即可实现CSV表格数据到Word文档的导入。以下是操作步骤示例:

  1. 导入所需模块。
  2. 创建Document对象从而创建一个Word文档。
  3. 使用Document.AddSection()方法再文档中创建一个节,再使用Section.AddTable()方法在节中创建一个表格。
  4. 创建表头单元格文本和数据行单元格文本的段落样式。
  5. 将表头数据写入表格并设置格式。
  6. 将其他数据写入表格并设置格式。
  7. 使用Table.AutoFit(AutoFitBehaviorType)方法设置表格自动对齐方式。
  8. 使用Document.SaveToFile()方法保存文档。
  9. 释放资源。

代码示例

python 复制代码
from spire.doc import *
import csv

# 读取CSV表格数据
with open('Sample.csv', 'r', encoding='utf-8') as file:
    reader = csv.reader(file)
    tableData = []
    for row in reader:
        tableData.append(row)

# 创建Document实例
doc = Document()

# 添加一个章节和一个表格
section = doc.AddSection()
table = section.AddTable()

# 为表头和单元格创建段落样式
headerStyle = ParagraphStyle(doc)
headerStyle.Name = "TableHeader"
headerStyle.CharacterFormat.FontName = "Arial"
headerStyle.CharacterFormat.FontSize = 12
headerStyle.CharacterFormat.Bold = True
doc.Styles.Add(headerStyle)
cellStyle = ParagraphStyle(doc)
cellStyle.Name = "TableCell"
cellStyle.CharacterFormat.FontName = "Arial"
cellStyle.CharacterFormat.FontSize = 11
doc.Styles.Add(cellStyle)

# 向表格添加表头行
headerRow = tableData[0]
tableRow = table.AddRow()
for cell in headerRow:
    tableCell = tableRow.AddCell()
    paragraph = tableCell.AddParagraph()
    paragraph.AppendText(cell)
    paragraph.ApplyStyle(headerStyle.Name)
    tableCell.CellFormat.VerticalAlignment = VerticalAlignment.Middle
    tableCell.CellFormat.Borders.BorderType(BorderStyle.Single)
    tableCell.CellFormat.Borders.Color = Color.get_Black()
    tableCell.CellFormat.Borders.LineWidth(1.8)

# 向表格添加数据行
for row in tableData[1:]:
    tableRow = table.AddRow()
    for cell in row:
        tableCell = tableRow.Cells[row.index(cell)]
        paragraph = tableCell.AddParagraph()
        paragraph.AppendText(cell)
        paragraph.ApplyStyle(cellStyle.Name)
        tableCell.CellFormat.VerticalAlignment = VerticalAlignment.Middle
        tableCell.CellFormat.Borders.BorderType(BorderStyle.Single)
        tableCell.CellFormat.Borders.Color = Color.get_Black()
        tableCell.CellFormat.Borders.LineWidth(0.8)

# 自动调整表格大小
table.AutoFit(AutoFitBehaviorType.AutoFitToWindow)

# 保存文档
doc.SaveToFile("output/CSVToWordTable.docx", FileFormat.Docx2019)
doc.Close()

结果文档

用Python导入Excel数据到Word表格

将Excel文件表格数据导入Word文档也可以用相似的操作进行。注意需要使用Spire.XLS for Python(PyPI:pip install Spire.XLS)导入Excel工作表数据,然后写入Word文档表格。以下是操作步骤:

  1. 导入所需模块。
  2. 创建Document对象从而创建一个Word文档。
  3. 使用Document.AddSection()方法再文档中创建一个节,再使用Section.AddTable()方法在节中创建一个表格。
  4. 创建Workbook对象并使用Workbook.LoadFromFile()方法载入Excel文件。
  5. 使用Workbook.Worksheets.get_Item()方法获取工作表。
  6. 创建表头单元格文本和数据行单元格文本的段落样式。
  7. 将表头数据写入表格并设置格式。
  8. 将其他数据写入表格并设置格式。
  9. 使用Table.AutoFit(AutoFitBehaviorType)方法设置表格自动对齐方式。
  10. 使用Document.SaveToFile()方法保存文档。
  11. 释放资源。

代码示例

python 复制代码
from spire.doc import Document, ParagraphStyle, VerticalAlignment, BorderStyle, Color, FileFormat
from spire.xls import Workbook

# 创建Document实例
doc = Document()

# 添加一个章节和一个表格
section = doc.AddSection()
table = section.AddTable()

# 创建Workbook实例并加载一个Excel文件
workbook = Workbook()
workbook.LoadFromFile("Sample.xlsx")

worksheet = workbook.Worksheets.get_Item(0)

# 为表头和单元格创建段落样式
headerStyle = ParagraphStyle(doc)
headerStyle.Name = "TableHeader"
headerStyle.CharacterFormat.FontName = "Arial"
headerStyle.CharacterFormat.FontSize = 12
headerStyle.CharacterFormat.Bold = True
doc.Styles.Add(headerStyle)
cellStyle = ParagraphStyle(doc)
cellStyle.Name = "TableCell"
cellStyle.CharacterFormat.FontName = "Arial"
cellStyle.CharacterFormat.FontSize = 11
doc.Styles.Add(cellStyle)

print(worksheet.AllocatedRange.ColumnCount)
print(worksheet.AllocatedRange.ColumnCount)

headerRow = table.AddRow()
for i in range(worksheet.AllocatedRange.ColumnCount):
    cell = headerRow.AddCell()
    paragraph = cell.AddParagraph()
    paragraph.AppendText(worksheet.AllocatedRange.get_Item(1, i + 1).Text)
    paragraph.ApplyStyle(headerStyle.Name)
    cell.CellFormat.VerticalAlignment = VerticalAlignment.Middle
    cell.CellFormat.Borders.BorderType(BorderStyle.Single)
    cell.CellFormat.Borders.Color = Color.get_Black()
    cell.CellFormat.Borders.LineWidth(1.8)

for j in range(1, worksheet.AllocatedRange.RowCount):
    dataRow = table.AddRow()
    for k in range(worksheet.AllocatedRange.ColumnCount):
        cell = dataRow.Cells.get_Item(k)
        paragraph = cell.AddParagraph()
        paragraph.AppendText(worksheet.AllocatedRange.get_Item(j + 1, k + 1).Value)
        paragraph.ApplyStyle(cellStyle.Name)
        cell.CellFormat.VerticalAlignment = VerticalAlignment.Middle
        cell.CellFormat.Borders.BorderType(BorderStyle.Single)
        cell.CellFormat.Borders.Color = Color.get_Black()
        cell.CellFormat.Borders.LineWidth(0.8)

# 自动调整表格大小
table.AutoFit(AutoFitBehaviorType.AutoFitToWindow)

# 保存文档
doc.SaveToFile("output/ExcelTableToWord.docx", FileFormat.Docx2019)
doc.Close()

结果文档

本文介绍了如何使用Python将CSV和Excel表格数据导入Word文档并创建表格。

更多Word文档处理技巧请前往Spire.Doc for Python教程查看。

相关推荐
量化吞吐机2 小时前
会写代码之后,量化学习还要补上交易判断
人工智能·python
lie..2 小时前
30天从零开始学AI应用开发(Day 1):机器学习、深度学习、大模型,到底是个啥关系
人工智能·python·大模型
Ivanqhz2 小时前
Unigram 算法
开发语言·人工智能·python·深度学习·mlir
Jazz_z3 小时前
如何用 C# 读取 Word 中的表格数据
开发语言·c#
冯一川3 小时前
Python 实现与 Ollama 运行的模型对话
人工智能·python
车间溜盖子3 小时前
TE(TEC 半导体制冷片)Qc / Qh 冷热面基础定义
python
天赐范式3 小时前
天赐范式第168天:让子代开始从父代肩膀上演化——跨代β传递demo与完整代码
python·数字生命·天赐范式·动态运行时·跨代β传递·可继承性验证·digitallife
刘天远3 小时前
Agent系统接入编排:评分模型、状态机与Python门禁
数据库·人工智能·python
郝学胜-神的一滴3 小时前
C++20模板元编程 04:变量模板 别名模板与模板Lambda实战
服务器·开发语言·数据结构·c++·程序人生
驭渊的小故事3 小时前
Java 项目-jckson序列化工具
java·开发语言