【问题标题】:read file content and write one of excel cell读取文件内容并写入excel单元格之一
【发布时间】:2021-09-03 10:17:01
【问题描述】:

有什么办法可以写python脚本

读取文件内容并在excel单元格中写入相同内容。

示例: 猫文件.txt -->

这是文件

以上文字内容需要写在excel单元格中。请推荐

【问题讨论】:

  • 您到底想在这里实现什么?我没有从你的问题中得到它。你能恰当地举个例子吗?
  • 您的意思是复制文件内容并将它们粘贴到 Excel 单元格中吗?
  • 先写python脚本读取文件
  • 是的@virxen 完全正确
  • 如果可以的话,能否分享一下代码。

标签: python python-3.x excel pandas xlsxwriter


【解决方案1】:

1)读取文件内容

f=open("txt.txt","r",encoding="utf8")
a=f.readlines()

2)发送到excel单元格

from xlsxwriter import *
a="testing"
filename="test.xlsx"
wb = Workbook(filename)
sheet1 = wb.add_worksheet()
cell_format = wb.add_format({'bold': False})
cell_format.set_font_size(12)
sheet1.set_column(0, 0, 50, cell_format)
sheet1.write(0, 0, a)
wb.close()

3) 并作为一个程序

from xlsxwriter import *
f=open("txt.txt","r",encoding="utf8")
b=f.readlines()
a="".join(b)
filename="test.xlsx"
wb = Workbook(filename)
sheet1 = wb.add_worksheet()
cell_format = wb.add_format({'bold': False})
cell_format.set_font_size(12)
cell_format.set_text_wrap()
sheet1.set_column(0, 0, 50, cell_format)
sheet1.write(0, 0, a)
wb.close()

你需要安装 --> https://pypi.org/project/XlsxWriter/

【讨论】:

  • from xlsxwriter import * a="testing" filename="test.xlsx" wb = Workbook(filename) sheet1 = wb.add_worksheet() cell_format = wb.add_format({'bold': False}) cell_format.set_font_size(12) sheet1.set_column(0, 0, 50, cell_format) sheet1.write(0, 0, a) wb.close() ... 结果将在 excel 的第一列和第一行中为“testing”,但您已经将值设置为“testing”
  • 它的 2 个不同的代码。只需通过删除 a="testing" 将它们合并为一个
  • 文件“/usr/local/lib/python3.9/site-packages/xlsxwriter/worksheet.py”,第 503 行,在 _write f = float(token) TypeError: float() argument must是字符串或数字,而不是'list' 在处理上述异常的过程中,发生了另一个异常:
  • readline() returns bracket 可能是这个问题。 ...其打印值为 ['Hello']
  • with open('txt.txt') as f: a = f.read() 这工作正常
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-21
  • 1970-01-01
相关资源
最近更新 更多