python 操作 excel 文件

版权声明:https://blog.csdn.net/qq_26877377 https://blog.csdn.net/qq_26877377/article/details/86507453

官方 地址 :http://www.python-excel.org/

使用 xlsxwriter (只能写 不能读取)来进行写成.xlsx 文件

可以使用xlrd 写成 xls 文件

 

简单 demo 如下:

import xlsxwriter, csv

# 创建excel 对象

workbook = xlsxwriter.Workbook('Expenses03.xlsx')
worksheet = workbook.add_worksheet()

# 添加数字格式
# money_format = workbook.add_format({'num_format': '#,##0'})

# 设置宽度
worksheet.set_column(1, 1, 15)

# 添加头
worksheet.write('A1', 'Item')
worksheet.write('B1', 'Date')
worksheet.write('C1', 'Cost')

# Some data we want to write to the worksheet.

# 从第二行第一个单元格写数据
row = 1

with open('需要转换的csv文件/周末每小时_wap_人数.csv', 'r', encoding='gbk') as f:
    read = csv.reader(f)
    for line in read:
        col = 0
        for item in line:
            try:
                item = int(item)
                worksheet.write_number(row, col, item)  # 按照数字格式去写
            except:
                worksheet.write(row, col, item) # 用字符串格式写入

            # worksheet.write_string(row, col, item)
            col += 1
        row += 1

workbook.close()
import csv,xlwt


def csv_to_xlsx():
    with open('需要转换的csv文件/周末每小时_wap_人数.csv', 'r', encoding='gbk') as f:
        read = csv.reader(f)
        workbook = xlwt.Workbook()
        sheet = workbook.add_sheet('data')  # 创建一个sheet表格
        l = 0
        for line in read:
            r = 0
            print(line)
            for i in line:
                try:
                    i = int(i)
                except:
                    pass
                sheet.write(l, r, i)  # 一个一个将单元格数据写入
                r = r + 1
            l = l + 1

        workbook.save("数据结果2")  # 保存Excel 格式


if __name__ == '__main__':
    csv_to_xlsx()

 

展开阅读全文

没有更多推荐了,返回首页