python pandas 读取文件 写入文件excel

  • 读取数据
import pandas as pd
import collections
def readLocationCodeForExcel():
    read_file = r"test.xlsx"
    sheet_names = {"库位码","地堆码"}

    sheet_data = pd.ExcelFile(read_file) #读取sheet数据
   #sheet列表
    read_sheet_data = sheet_data.sheet_names
    #查看缺少的sheet
    lack_set = sheet_names - set(read_sheet_data)
    #初始化数组
    read_code_array = np.array([])
    row_col_array = np.array([])
    region_array = np.array([])
    if lack_set:
        logger.info("缺少的sheet将不会查询:{}".format(lack_set))

    sheet_names = sheet_names - lack_set
    for sheet_name in sheet_names:

        df = pd.read_excel(read_file,sheet_name=sheet_name,dtype=str)
        if sheet_name in df.keys():
            #print(type(df[sheet_name].values))
            #read_code_list = read_code_list + list(df[sheet_name].values)
            read_code_array = np.hstack((read_code_array,df[sheet_name].values))# 读取 地堆 列 水平组合 有点像字符组合 str1=str1+strx
            row_col_array = np.hstack((row_col_array,df["位置"].values))
            region_array = np.hstack((region_array,df["区域名称"].values))
    return read_code_array, row_col_array,region_array
  • 写入数据
import pandas as pd
import collections

def wirteInventoryDataToExcelTest(data):
    write_file = "path_to_file.xlsx"
    #data = (1,2,3)

    df = pd.DataFrame(data)
    writer =  pd.ExcelWriter(write_file)
    df.to_excel(writer,index=False,startrow=0) # index=False不写入序号
    #df1.to_excel(writer)
    writer.save()

 #region_array2 等 为 np.array([....]) 数据 其中 region_array2[0] 存的是excel表头,前面数组同样
 data_dict = collections.OrderedDict() #把字典变为有序字典 用于写入excel数据有顺序写入
 data_dict[region_array2[0]] = np.delete(region_array2, 0)
data_dict[row_col_array2[0]] = np.delete(row_col_array2, 0)
data_dict[locationCode_array[0]] = np.delete(locationCode_array,0)
data_dict[identifyCode_array[0]] = np.delete(identifyCode_array, 0)
data_dict[p_qty_array[0]] =  np.delete(p_qty_array, 0)
data_dict[unitName_array[0]] = np.delete(unitName_array, 0)
data_dict[p_name_array[0]] = np.delete(p_name_array, 0)
data_dict[sellAttributeValues_array[0]] = np.delete(sellAttributeValues_array, 0)


 wirteInventoryDataToExcelTest(data_dict)

posted on 2019-07-12 12:02  游荡的鱼  阅读(4763)  评论(0编辑  收藏  举报

导航