表格的读取和写入

该代码示例展示了如何使用Python的xlrd和xlwt库读取和写入Excel文件,以及使用pandas读取CSV文件。Readxlsx函数读取Excel文件的特定列,而Readcsv函数则读取CSV文件中的特定字段。write函数用于创建一个新的Excel工作表并写入数据。Write_excel类允许在已有Excel文件上追加数据,保留原有样式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

import os
import xlrd
import xlwt
import pandas as pd

def Readxlsx(excel_name):
    data = xlrd.open_workbook(excel_name)
    
    table = data.sheets()[0]
    
    table.row_values(i)
    table.col_values(i)
    
    nrows = table.nrows
    ncols = table.ncols
    
    id = table.col_values(0)[2:]
    data = table.col_values(1)[2:]
    value = table.col_values(4)[2:]
    


def Readcsv(excel_name):
    #data = pd.read_csv(excel_name, encoding='gb18030',error_bad_lines=False)
    data = pd.read_csv(excel_name, on_bad_lines='skip')
    video_id_list = data['内容id']
    video_describe_list = data['标题']
    image_url_list = data['封面图']
    video_url_list = data['url']
    
def write():
    #写表格
    f = xlwt.Workbook()
    sheet = f.add_sheet('sheet',cell_overwrite_ok=True)
    #写第一行
    for i in range(0,len(row0)):
        # sheet1.write(0,i,row0[i],set_style('Times New Roman',220,True))
        sheet.write(0,i,'内容')
   
    f.save('result.xls')

def write_csv():
    import pandas as pd
    data = {'col1':[1,2,3,'aa'],'col2':[3,1,3,'bb']}
    data_df = pd.DataFrame(data)
    data_df.to_csv('data_df.csv',index=False,header=True)
    #index表示设定是否需要行索引,设定为FALSE表明不需要,就不会生成新的行索引
    #header表明是否需要列索引,设定为True(默认设置)表明需要,那么之前df的列标签就会保存。
    pd.read_csv('data_df.csv', encoding='gb18030')
	#~~~~~~~~~~~~~~~~
	#   col1  col2
	#0   1     3
	#1   2     1
	#2   3     3
	#3  aa    bb

def set_style(name,height,bold=False):
    style = xlwt.XFStyle()
    font = xlwt.Font()
    font.name = name
    font.bold = bold
    font.color_index = 4
    font.height = height
    style.font = font
    return style

续写

import xlrd
import xlwt
from xlutils.copy import copy

class Write_excel():
    def __init__(self, excel_name):
        if os.path.exists(excel_name):

            # 用 xlrd 提供的方法读取一个excel文件
            rexcel = xlrd.open_workbook(excel_name,formatting_info=True) # 保留原有样式
            # 用 xlrd 提供的方法获得现在已有的行数
            rows = rexcel.sheets()[0].nrows 
            # 用 xlutils 提供的copy方法将 xlrd 的对象转化为 xlwt 的对象
            self.f = copy(rexcel) 
            # 用 xlwt 对象的方法获得要操作的 sheet
            self.sheet = self.f.get_sheet(0) 
        else:
            #写表格
            self.f = xlwt.Workbook()
            self.sheet = self.f.add_sheet('sheet',cell_overwrite_ok=True)
        self.excel_name = excel_name
    def __call__(self, row_id, col_id, token):
        if not token == '':
            self.sheet.write(row_id,col_id,token)
            self.f.save(self.excel_name)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值