用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. 释放资源。

代码示例

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导入CSV到Word

用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. 释放资源。

代码示例

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导入Excel数据到Word

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

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

  • 4
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值