用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教程查看。

相关推荐
dialect_4 小时前
KMP算法
开发语言·c++·算法
总要学点什么5 小时前
第89篇:三维特效-螺旋圆效果——让螺旋臂卷起一圈圈外扩的涟漪
开发语言·javascript·ecmascript·webgl·cesium·空间分析·1024程序员节
前端精髓5 小时前
结构化输出with_structured_output(抽卡)
python·langchain
尹人入圣6 小时前
目前热门的IP驱动产业新场景新工具
网络·python·网络协议·tcp/ip
开开心心_Every6 小时前
快速隐藏程序工具自定义快捷键一键切换
java·开发语言·前端·spring·智能手机·word·intellij-idea
chenbingjie_c6 小时前
C++ 多态完全指南:从虚函数重写到虚函数表原理
开发语言·c++
Nuanyt7 小时前
Agent 学习笔记(下篇三):上线工程、进阶选择与操作界面(Stage 7 / 7.5 / 8 + 延伸路线)
笔记·python·学习·memory·aiagent·harness
吴卫斌7 小时前
定投ETF实战指南(四):行业/主题ETF——定投的“进攻端“
开发语言·python·股票·量化
2601_967987377 小时前
Python——入门级(定义功能def函数)
python·函数·可变参数·默认参数·关键字参数
超级架构师8 小时前
PRAXO-CORE 2.5.0:用 conformance 和显式边界构建 Go Agent 框架
开发语言·人工智能·后端·golang·ai编程·智能体框架·praxo-core