pythonTXT转excel
时间: 2023-10-11 13:08:08 浏览: 106
python实现TXT文件批量处理-分割、翻译和格式转excel
Python可以通过使用xlwt库或openpyxl库来实现将文本转换为Excel文件。
使用xlwt库的代码示例如下:
```python
import xlwt
def txt_to_xls(txt_path, xls_path):
with open(txt_path, 'r', encoding='utf-8') as f:
content = f.read()
lines = [line.strip() for line in content.split('\n') if line.strip()]
workbook = xlwt.Workbook()
worksheet = workbook.add_sheet('Sheet1')
for i, line in enumerate(lines):
cols = line.split('\t')
for j, col in enumerate(cols):
worksheet.write(i, j, col)
workbook.save(xls_path)
txt_path = 'example.txt'
xls_path = 'example.xls'
txt_to_xls(txt_path, xls_path)
print('转换完成!')
```
使用openpyxl库的代码示例如下:
```python
from openpyxl import Workbook
def txt_to_xlsx(txt_path, xlsx_path):
wb = Workbook()
ws = wb.active
with open(txt_path, 'r') as f:
content = f.read().replace(',', '\t')
lines = content.split('\n')
for line in lines:
item = line.split('\t')
ws.append(item)
wb.save(xlsx_path)
txt_path = 'test.txt'
xlsx_path = 'result.xlsx'
txt_to_xlsx(txt_path, xlsx_path)
print('转换完成!')
```
阅读全文