1070148808 / huaweiStudyJava

0 stars 0 forks source link

excel处理 #21

Closed 1070148808 closed 5 years ago

1070148808 commented 5 years ago
# -*-coding:utf-8-*-
__author__ = 'z00464153'
import xlwt
from xlrd import *
import copy
import time

# 时间
def get_time():
    return time.strftime('%Y-%m-%d-%H-%M-%S', time.localtime(time.time()))

# 删除无用信息
def delete_bad_str(str):
    str = str.replace("<p>", " ").replace("&nbsp;", " ").replace("</p>", " ").replace("<font", " ").replace("</font>",
                                                                                                            " ")
    return str

# ;分号后增加回车
def add_enter_str(str):
    list = str.split(";")
    str1 = "\n".join(list)
    return str1

def deal():
    rb = open_workbook("名字.xls")  # read excel
    rs = rb.sheets()[0]  # read sheet
    test_col = rs.col_values(1)  # read col 从1开始  第一列list
    # row_values(0) 行值list,0:行号,后面可以接两个参数,表示列数范围 上述方法也可

    # rs.name 名字
    # rs.ncols 列数
    # rs.nrows 行数

    # 取一个单元格值
    # print(table1.cell(1, 2).value)
    # print(table1.cell_value(1, 2))
    # print(table1.row(1)[2]).value
    # print(table1.col(2)[1]).value
    # 取一个单元格类型
    # print(table1.cell(1, 2).ctype)
    # print(table1.cell_type(1, 2))
    # print(table1.row(1)[2].ctype)

    test_col_copy = copy.deepcopy(test_col)  # copy to deal 复制处理内容

    # 创建新的excel
    wb = xlwt.Workbook()  # write excel
    ws = wb.add_sheet('Sheet1')  # write sheet

    # 复制原excel
    # wb = copy(rb)

    # rb.sheet_names()  # 获取sheet名称

    # 循环处理
    for content in test_col_copy:  # 用复制的数组循环
        if content.startswith("1111111") or content.startswith("222222"):
            test_col.remove(content)  # 用原数组清洗数据
    # 现在只要把原数组数据写入新的excel即可

    # 写出
    for i in range(0, len(test_col)):
        ws.write(i, 0, test_col[i])  # 第一个参数为行数 第二个为列
        ws.write(i, 1, delete_bad_str(test_col[i]))  # 写入数据

        # 把内容保存为别的文件
        stra = "test" + str(i) + ".java"
        f = open(stra, 'w')  # 若是'wb'就表示写二进制文件
        f.write(test_col[i])
        f.close()

    # 保存
    wb.save("deal_result.xls")
    print("write finished")