xlsx批量转为utf8的csv

(金庆的专栏)

策划的配置表为 xlsx 表格,可以有注释,公式。
服务器和客户端使用的配置文件需要转成 csv 文件。
使用 WPS 另存无法批量转换,并且结果不是utf8编码的,还需要用Notepad++转编码。

除了 xlsx 转为 csv, 其他格式文件保持原样,如 *.ini, *.xml, *.lua.
server/ 子目录特殊处理,不能复制到客户端。

用python脚本实现,依赖 openpyxl 库。

#!/usr/bin/env python
# coding: utf-8
# datatab.py
# 从策划配置表目录 game\Design\配置表\”
#   生成服务器的 game\Program\server\six\datatab\” 目录,
#   和客户端的 game\Program\client\Assets\Config\” 目录。
#   所有xlsx文件生成csv文件,其他文件原样复制。
#   其中 server\ 目录特殊处理,仅对服务器有效,客户端跳过。
#
# 依赖openpyxl库:http://openpyxl.readthedocs.org/en/latest/
# 参考代码 http://segmentfault.com/q/1010000003006437?_ea=273128
# 测试环境:Python3.4

# Usage: datatab.py <game dir>
# Example: datatab.py "d:\game"
# <game dir> 是根目录,包含Design/, Program/ 目录。

from openpyxl import Workbook
from openpyxl.compat import range
from openpyxl.cell import get_column_letter
from openpyxl import load_workbook
import csv
import os
import sys
import shutil

def xlsx2csv(filename):
    # try:
        xlsx_file_reader = load_workbook(filename = filename, data_only = True)
        for sheet in xlsx_file_reader.get_sheet_names():
            # 仅第1个sheet输出到一个csv文件中,文件名后缀替换为.csv
            csv_filename = os.path.splitext(filename)[0] + '.csv'
            csv_file = open(csv_filename, 'w', encoding='utf8', newline='')
            csv_file_writer = csv.writer(csv_file)
            sheet_ranges = xlsx_file_reader[sheet]
            for row in sheet_ranges.rows:
                row_container = []
                for cell in row:
                    row_container.append(cell.value)
                csv_file_writer.writerow(row_container)
            # End of for row.
            csv_file.close()
            break  # 仅输出第1个sheet
        # End of for sheet.
    # End of try.
    # except Exception as e:
    #    print(e)
# End of xlsx2csv().

def datatab_convert(game_dir):
    '''从 game\Design\配置表\ 输出到
      game\Program\server\six\datatab\
      game\Program\client\Assets\Config\
    '''
    design_dir = os.path.join(game_dir, 'Design/配置表/')
    server_dir = os.path.join(game_dir, 'Program/server/six/datatab/')
    client_dir = os.path.join(game_dir, 'Program/client/Assets/Config/')
    
    # 删除旧文件。
    print("Delete " + server_dir)
    try:
        shutil.rmtree(server_dir)
    except:
        pass
    print("Delete " + client_dir)
    try:
        shutil.rmtree(client_dir)
    except:
        pass    

    # 生成server文件
    print("Creating " + server_dir)
    shutil.copytree(design_dir, server_dir)
    files = get_files(server_dir)
    convert_files(files)
    
    # 复制client文件
    print("Copy " + client_dir)
    shutil.copytree(server_dir, client_dir)
    shutil.rmtree(os.path.join(client_dir, 'server/'))
    print("Done. Total files: %d" % len(files))
# End of datatab_convert().    

def get_files(dir):
    '''Get a list of files under input dir.'''
    result = []
    for root,dirs,files in os.walk(dir):
        for f in files:
            result.append(os.path.join(root, f))
    return result
# End of get_files().            

def convert_files(files):
    '''转换一批文件.
    files 是列表,元素为完整路径名。
    '''
    for f in files:
        ext = os.path.splitext(f)[1].lower()
        if '.xlsx' != ext:
            print(f + " -> keep")
            continue
        print(f + " -> csv")
        xlsx2csv(f)
        os.remove(f)
# End of convert_files().        

if __name__ == '__main__':
    if len(sys.argv) != 2:
        print('usage: datatab <game dir>')
    else:
        datatab_convert(sys.argv[1])
    sys.exit(0)

# Usage: datatab.py <game dir>
# Example: datatab.py "d:\game"
# <game dir> 是SVN根目录,包含Design/, Program/ 目录。

为方便使用,将datatab.py 打包成 exe, 这样不能安装Python就能运行。
下载并安装Python3, 安装openpyxl包,保证本地可以运行 datatab.py.
下载并安装PyInstaller:
    pip install pyinstaller
运行
    pyinstaller --onefile datatab.py

ImportError: No module named 'jdcal'
可能openpyxl安装时自带的jdcal无法找到,删除
C:\Python34\Lib\site-packages\jdcal-1.0-py3.4.egg
重新安装:pip install jdcal

xlsx批量转为utf8的csv的更多相关文章

  1. R语言︱用excel VBA把xlsx批量转化为csv格式

    笔者寄语:批量读取目前看到有以下几种方法:xlsx包.RODBC包.批量转化成csv后读入.本章来自博客:http://www.cnblogs.com/weibaar/p/4506144.html 在 ...

  2. 批量将Java源代码文件的编码从GBK转为UTF-8

    主要参考: http://blog.csdn.net/liu_qiqi/article/details/38706497 使用common io批量将java编码从GBK转UTF-8 http://w ...

  3. Eclipse:批量将Java源代码文件的编码从GBK转为UTF-8

    很简单的几行代码,就可以批量将GBK格式的java文件转为UTF-8格式. 基本上所有文本文件的编码转换都可以采用这种方式. import java.io.File; import java.io.I ...

  4. 将汉字转为UTF-8编码

    01./** 02. * 将文件名中的汉字转为UTF8编码的串,以便下载时能正确显示另存的文件名. 03. * @param s 原文件名 04. * @return 重新编码后的文件名 05. */ ...

  5. java 将GBK编码文件转为UTF-8编码

    需要commons-io-2.0.1.jar public class Test { public static void main(String args[]) throws IOException ...

  6. php将unicode编码转为utf-8方法

    介绍 在前端开发中,为了让中文在不同的环境下都能很好的显示,一般是将中文转化为unicode格式,即\u4f60,比如:"你好啊"的 unicode编码为"\u4f60\ ...

  7. 解决 Excel 打开 UTF-8 编码 CSV 文件乱码的 BUG

    解决 Excel 打开 UTF-8 编码 CSV 文件乱码的 BUG zoerywzhou@163.com http://www.cnblogs.com/swje/ 作者:Zhouwan 2017-6 ...

  8. String 字符串中含有 Unicode 编码时,转为UTF-8

    1.单纯的Unicode 转码 String a = "\u53ef\u4ee5\u6ce8\u518c"; a = new String(a.getBytes("UTF ...

  9. php字符编码转换之gb2312转为utf8(转)

    在php中字符编码转换我们一般会用到iconv与mb_convert_encoding进行操作,但是mb_convert_encoding在转换性能上比iconv要差很多哦.string iconv ...

随机推荐

  1. spring mvc中的注解说明

    注解扫描 context:component-scan 包扫描 <context:component-scan base-package="org.bdp"> < ...

  2. Python3玩转儿 机器学习(1)

    机器学习的基础概念 数据 著名的鸢尾花数据 https://en.wikipedia.org/wiki/lris_flower_data_set          lris setossa       ...

  3. 获取Avrix上Computer Vision and Pattern Recognition的论文,进一步进行统计分析。

    此文主要记录我在18年寒假期间,收集Avrix论文的总结 寒假生活题外   在寒假期间,爸妈每天让我每天跟着他们6点起床,一起吃早点收拾,每天7点也就都收拾差不多.   早晨的时光是人最清醒的时刻,而 ...

  4. [CQOI 2010]扑克牌

    Description 你有n种牌,第i种牌的数目为ci.另外有一种特殊的 牌:joker,它的数目是m.你可以用每种牌各一张来组成一套牌,也可以用一张joker和除了某一种牌以外的其他牌各一张组成1 ...

  5. [JSOI2007]文本生成器

    题目描述 JSOI交给队员ZYX一个任务,编制一个称之为“文本生成器”的电脑软件:该软件的使用者是一些低幼人群,他们现在使用的是GW文本生成器v6版. 该软件可以随机生成一些文章―――总是生成一篇长度 ...

  6. POI SZP

    贪心: 初始所有点为白色,对于点i,若a[i]为白色则将其染成与i不同的颜色. 证明:若点i确定为白色,a[i]染白色也只能提供一个黑点,故a[i]染黑色不会差:若所有指向i的点均为黑色,则i只能是白 ...

  7. UVA - 11107:Life Forms

    后缀数组height+二分 #include<cstdio> #include<cstdlib> #include<algorithm> #include<c ...

  8. 【Luogu P2709 小B的询问】莫队

    题目描述 小B有一个序列,包含N个1~K之间的整数.他一共有M个询问,每个询问给定一个区间[L..R],求Sigma(c(i)^2)的值,其中i的值从1到K,其中c(i)表示数字i在[L..R]中的重 ...

  9. Codeforces278E Tourists

    来自FallDream的博客,未经允许,请勿转载,谢谢. 给定一张无向图,有点权,要支持单点修改点权和询问从一个点到另一个点不重复经过节点的路径上点权最小值的最小值. n,m<=10^5 考虑求 ...

  10. thymeleaf:局部变量 th:with

    当th:with被处理,firstPer变量创建一个局部变量和变量添加到map自上下文,以便它是用于评估和其他上下文中声明的变量从开始,但只有包含< div >标记的范围内. <di ...