2019-10-30 09:16

# 请问这段代码和我预期的结果不太一样，求大神帮忙看一下，谢谢。哪里的问题？

``````import os
import xlrd
import xlwt
from pip._vendor.distlib.compat import raw_input

# limit = raw_input('input limit number:')
limit = 500
savebook=r'D:\b\bb.csv'
#
# savebook = raw_input('input excel save path:')

if limit == '':
limit = 50  # 默认按100条拆分
print ('拆分数量: ' + str(limit))

limit = int(limit)

# '/Users/huqiang/Desktop/shoplist.xls'

# 获取sheet
table = data.sheets()[0]
# 行数
nrows = table.nrows
print(nrows)
# 列数
ncols = table.ncols
if nrows % limit != 0:
sheets = (nrows // limit)+1
else:
sheets=nrows // limit
# sheets = (nrows // limit)+1
print(sheets)
# print str(nrows) + '   ' + str(ncols)

# print table10.cell(nrows - 1, ncols - 1).value

workbook = xlwt.Workbook(encoding='ascii')

for i in range(0, int(sheets)):
print('**',i)

# print(row)
row_content = table.row_values(row + (i*50))
for col in range(0, ncols):
worksheet.write(row, col, row_content[col])
workbook.save(savebook)
``````

g)

• 点赞
• 写回答
• 关注问题
• 收藏
• 邀请回答

#### 1条回答默认 最新

• 二心TOT 2019-10-30 15:36
已采纳

就在你的代码基础上改了，写代码要把临界条件考虑完全

``````# -*- coding: UTF-8 -*-
import os
import xlrd
import xlwt
from pip._vendor.distlib.compat import raw_input

# limit = raw_input('input limit number:')
limit = 500
savebook=r'D:\b\bb.csv'
#
# savebook = raw_input('input excel save path:')

if limit == '':
limit = 50  # 默认按100条拆分
print ('拆分数量: ' + str(limit))

limit = int(limit)

# '/Users/huqiang/Desktop/shoplist.xls'

# 获取sheet
table = data.sheets()[0]
# 行数
nrows = table.nrows
print(nrows)
# 列数
ncols = table.ncols
if nrows % limit != 0:
sheets = (nrows // limit)+1
else:
sheets=nrows // limit
# sheets = (nrows // limit)+1
print('sheets:',sheets)
# print str(nrows) + '   ' + str(ncols)

# print table10.cell(nrows - 1, ncols - 1).value

workbook = xlwt.Workbook(encoding='ascii')

for i in range(0, int(sheets)):
print('**',i)
if sheets-1 == i:
for row in range(i*500, nrows):
# print(row)
row_content = table.row_values(row)
for col in range(0, ncols):
worksheet.write(row-i*500, col, row_content[col])
else:
for row in range(0, limit):
# print(row)
row_content = table.row_values(row + (i*500))
for col in range(0, ncols):
worksheet.write(row, col, row_content[col])

workbook.save(savebook)
``````
点赞 打赏 评论