> For the complete documentation index, see [llms.txt](https://kerasnoone.gitbook.io/garnet/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://kerasnoone.gitbook.io/garnet/gong-cheng-zhan/python/pandas/large-data/jiang-chao-da-biao-ge-cun-chu-wei-xlsx-ge-shi.md).

# 将超大表格存储为xlsx格式

## 问题描述

在使用pandas处理规模较大的数据时, 最后得到的`DataFrame`需要持久化为文件. 如果直接保存为`.csv`, `.json`这种存文本的文件, 最后得到的文件大小会很大.

如果最后得到的文件不是经常使用, 只是为了存储, 文件的大小就是我们要重点考虑的问题. 保存为存文本文件后压缩, 固然是一种方法, 但多了压缩以及使用时解压缩的步骤, 相当麻烦.

Excel表格对应的`.xlsx`格式存储的内容就是经过压缩的, 占用的体积会小很多. 因此保存为`.xlsx`格式是一个很好的选择.

> 要注意, .xlsx格式经过压缩后保存的体积小, 但读取时需要有对应的解压缩过程. 包含同样内容的.csv文件读取速度会比.xlsx快很多. 使用哪种格式, 要在速度和大小之间进行取舍.

但如果要保存的`DataFrame`很大, 直接使用`.to_excel()`方法会报如下的错误:

```
zipfile.LargeZipFile: Filesize would require ZIP64 extensions
```

## 问题原因

保存为`.xlsx`格式会调用`ZipFile`工具进行压缩. 当要存储的表格占用的原始大小超过**4GB**时, 需要在`ZipFile`工具初始化得时候指定`allowZip64`参数为`True`. 但默认的初始化时`False`, 因此会出现报错问题.

## 解决方法

手动指定保存使用的Writer.

```python
writer = pd.ExcelWriter('your_file_name.xlsx', engine='xlsxwriter')
data.to_excel(writer, sheet_name='Sheet1')
writer.book.use_zip64()
```

## 参考资料

* [LargeZipFile: Filesize would require ZIP64 extensions](https://stackoverflow.com/questions/63529670/would-require-zip64-extensions-largezipfile-filesize-would-require-zip64-ex)
