python中生成一个指定位置的目录:
def mkdir(path):
import os
path = path.strip()
path = path.rstrip("\\")
isExists = os.path.exists(path)
if isExists:
print(path + ' 目录已存在')
return False
else:
os.makedirs(path)
print(path + ' 创建成功')
return True
mkpath = "shen" #可以使用绝对路径和相对路径
mkdir(mkpath)
python中在指定目录下创建一个excel文件:
import xlsxwriter
#可以指定绝对路径和相对路径
workbook = xlsxwriter.Workbook('demo.xlsx')
# 创建工作表
worksheet = workbook.add_worksheet()
# Widen the first column to make the text clearer
# 设置一列或者多列单元属性
worksheet.set_column('A:A', 20)
# Add a bold format to use to highlight cells
# 在工作表中创建一个新的格式对象来格式化单元格,实现加粗
bold = workbook.add_format({'bold': True})
# write some simple text.
# 工总表写入简单文本
worksheet.write('A1', 'hello')
# Text with formatting
# 工作表写入带有格式的文本,加粗
worksheet.write('A2', 'World', bold)
# Write some numbers, with row/column notation #按照坐标写入
worksheet.write(2, 0, 123)
worksheet.write(3, 0, 123.456)
# Insert an image.
# 插入图片
worksheet.insert_image('B5', 'lena.png')
# 关闭工作薄
workbook.close()
excel合并单元格
# encoding=gbk
import xlsxwriter
# 自定义单元格格式
def set_merge_style(workbook, tag):
number_format, font_color, align = '', '', 'center'
if tag == 'head1':
bold, font_size, border = True, 14, 1
fg_color = '#4F81BD'
font_color = 'white'
else:
bold, font_size, border = True, 12, 1
fg_color = '#FFFFFF'
font_color = 'red'
number_format = '0.00%'
cell_format = workbook.add_format({
'bold': bold,
'font_size': font_size,
'border': border,
'align': align,
'valign': 'vcenter', # 垂直居中
'fg_color': fg_color, # 颜色填充
'num_format': number_format,
'font_color': font_color,
'font_name': '宋体',
})
return cell_format
workbook = xlsxwriter.Workbook('demo.xlsx')
worksheet = workbook.add_worksheet('表格1')
# 合并A列-N列,第一个参数是位置,第二个参数是内容,第三个参数是自定义格式
worksheet.merge_range('A1:N2', 'xx模型xx清单',set_merge_style(workbook, tag='head1'))
worksheet.merge_range('A3:N3', '次级标题1',set_merge_style(workbook, tag='head2'))
#设置行高,set_tow(行号,对应行高)
worksheet.set_row(0, 25)
worksheet.set_row(1, 25)
worksheet.set_row(2, 20)
workbook.close()