openxlsx包:读取/输出excel数据

本文介绍了一个简化处理.xlsx文件的R包,支持读取、写入和设置xlsx文件样式,无需依赖Java。文中详细讲解了如何使用read.xlsx()和write.xlsx()函数进行数据操作,并提供了高级样式设置方法。

可以非常方便地读取、写入、编辑.xlsx文件,无需设置java,同时输出的table样式比write.csv从看起来更加舒适。

其他非.xlsx的excel文件可另存为.xlsx文件后使用这个包


描述:

openxlsx simplifies the the process of writing and styling Excel xlsx files from R and removes the dependency on Java.

简化了处理xlsx文件的过程

可以用于读取xlsx文件,将数据写入到xlsx文件,设置xlsx文件的样式


1. 从xlsx文件中读取数据

(1)read.xlsx()函数

Read data from an Excel file or Workbook object into a data.frame


用法:

read.xlsx(xlsxFile, sheet = 1, startRow = 1, colNames = TRUE, rowNames = FALSE, 

detectDates = FALSE, skipEmptyRows = TRUE, skipEmptyCols = TRUE, 

rows = NULL, cols = NULL, check.names = FALSE, namedRegion = NULL, na.strings = "NA", fillMergedCells = FALSE)

常用参数:

xlsxFile:An xlsx file, Workbook object or URL to xlsx file. xlsx文件路径
sheet:The name or index of the sheet to read data from. sheet名或者数字索引
startRow:first row to begin looking for data. Empty rows at the top of a file are always skipped, regardless of the value of startRow. 从哪一行开始读入
colNames:If TRUE, the first row of data will be used as column names. 如果TRUE,则第一行作为列名
rowNames:If TRUE, first column of data will be used as row names. 如果TRUE,则第一列作为行名
skipEmptyRows:If TRUE, empty rows are skipped else empty rows after the first row containing data will return a row of NAs.是否跳过空白行,否则该行返回NA
skipEmptyCols:If TRUE, empty columns are skipped. 是否跳过空白列
rows:A numeric vector specifying which rows in the Excel file to read. If NULL, all rows are read. 数值型向量,读入哪些行,默认为全部读入
cols:A numeric vector specifying which columns in the Excel file to read. If NULL, all columns are read.数值型向量,读入哪些列,默认为全部读入

返回值:数据框


(2)readWorkbook()

Read data from an Excel file or Workbook object into a data.frame


用法:

readWorkbook(xlsxFile, sheet = 1, startRow = 1, colNames = TRUE,  rowNames = FALSE, 

detectDates = FALSE, skipEmptyRows = TRUE,  skipEmptyCols = TRUE, 

rows = NULL, cols = NULL, check.names = FALSE, namedRegion = NULL, na.strings = "NA", fillMergedCells = FALSE)


参数:同read.xlsx


与read.xlsx()函数的区别:

使用上应该是没有区别吧(其他不确定)

通过查看源码发现:read.xlsx()为泛型函数,而readWorkbook()函数在内部只调用read.xlsx函数。


2. 向xlsx文件中写入数据

(1)方案一:write.xlsx()

write a data.frame or list of data.frames to an xlsx file

用法:

write.xlsx(x, file, asTable = FALSE, ...)

参数:

x:object or a list of objects that can be handled by writeData to write to file
file:xlsx file name
asTable:write using writeDataTable as opposed to writeData
...:optional parameters to pass to functions:

常用的可选参数:

firstRow = TRUE:冻结第一行

colWidths = ‘auto’:自动设置列宽

如果需要使用粳稻的可选参数设置样式,可以选择使用方案二写入数据


(2)方案二:createWorkbook()+ addWorksheet()+ writeData()或writeDataTable()+ saveWorkbook()

创建Workbook - 插入sheet - 在sheet中写入数据 - 保存workbook

(2.1)创建新的workbook:createWorkbook(creator = Sys.getenv("USERNAME"))

参数:creator:Creator of the workbook (your name). Defaults to login username

返回值:workbook对象

(2.2)向workbook中插入新的sheet表:

addWorksheet(wb, sheetName, gridLines = TRUE, ...

(2.3)向sheet中写入数据

writeData(wb, sheet, x, startCol = 1, startRow = 1, xy = NULL, colNames = TRUE, rowNames = FALSE, headerStyle = NULL,...)

writeDataTable(wb, sheet, x, startCol = 1, startRow = 1, xy = NULL, colNames = TRUE, rowNames = FALSE, headerStyle = NULL,...)

Write to a worksheet and format as an Excel table.

(2.5)设置样式

createStyle():设置边框,字体,字号,背景色等,注意如果设置多行或者多列不连续,需要使用循环结果依次设置

addStyle():将样式添加到sheet上

freezePane():设置冻结窗格

setColwidths():设置行宽

(2.4)保存workbook

saveWorkbook(wb, file, overwrite = FALSE)


3. 使用options()设置样式(全局)

options("openxlsx.borderColour" = "black"):表格边框颜色
options("openxlsx.borderStyle" = "thin"):表格边框样式
options("openxlsx.dateFormat" = "mm/dd/yyyy"):日期格式
options("openxlsx.datetimeFormat" = "yyyy-mm-dd hh:mm:ss"):时间日期格式
options("openxlsx.numFmt" = NULL):
options("openxlsx.paperSize" = 9) ## A4
options("openxlsx.orientation" = "portrait") ## page orientation


4. 额外设置样式

(1)创建一个style对象createStyle()

createStyle(fontName = NULL, fontSize = NULL, fontColour = NULL,
  numFmt = "GENERAL", border = NULL,
  borderColour = getOption("openxlsx.borderColour", "black"),
  borderStyle = getOption("openxlsx.borderStyle", "thin"), bgFill = NULL,
  fgFill = NULL, halign = NULL, valign = NULL, textDecoration = NULL,
  wrapText = FALSE, textRotation = NULL, indent = NULL)

(2)将创建的style对象用于某些单元格:addStyle(wb, sheet, style, rows, cols, gridExpand = FALSE, stack = FALSE)

(3)openXL(wb) ## opens a temp version 设置好样式后浏览下

(4)冻结窗格:freezePane(wb, sheet, firstActiveRow = NULL, firstActiveCol = NULL, firstRow = FALSE, firstCol = FALSE)

(5)设置列宽:setColWidths(wb, sheet, cols, widths = 8.43, hidden = rep(FALSE, length(cols)), ignoreMergedCells = FALSE)

如需自动列宽,将widths = ‘auto’



未解决问题:

在数据量较大时, 对数据框格式的数据使用write.xlsx()或其他写入excel文件的函数时,第一次可以调用成功,但是把project关闭重新打开后,经常会出现

Error in is.nan(tmp) : default method not implemented for type 'list'

<think>好的,用户想用C++和openxlsx读取Excel数据并存到数组里。首先,我需要确认openxlsx是否支持C++。不过根据我的知识,openxlsx其实是R语言的库,不是C++的。可能用户搞错了库的名字。那C++处理Excel常用的库有哪些呢?比如LibXL、OpenXLSX(如果是这个的话,可能需要确认)、或者使用COM对象操作Excel,或者用Qt的QAxObject。 接下来,用户需要示例代码。假设用户确实是指OpenXLSX这个库,但不确定是否有C++版本。可能需要查证。假设存在,那么代码结构可能涉及打开工作簿、选择工作表、读取单元格数据到数组。如果不存在,可能需要推荐其他库,比如LibXL或者使用xlsxwriter类似的C++库。 另外,用户提供的引用中有Python和Java的例子,但用户明确需要C++,所以需要调整。例如,引用[1]是Python写入Excel,引用[2]是Java读取Excel,可能对理解需求有帮助,但代码结构不同。 可能需要检查OpenXLSX的官方文档是否存在C++支持。如果不存在,可能需要建议替代方案。比如LibXL,或者使用COM(在Windows下)。或者使用其他库如xlnt。 假设用户坚持用OpenXLSX,可能需要说明该库是R的,但可以推荐其他C++库。例如,xlnt是一个现代C++库,支持读写xlsx。然后给出使用xlnt的示例代码。 步骤大概是:含头文件,打开工作簿,获取工作表,遍历行和列,读取单元格数据存入数组。需要注意错误处理,比如文件是否存在,单元格是否为空等。 另外,需要处理不同数据类型,比如数字、字符串等,可能需要根据用户需求转换。示例中可能使用字符串数组来存储,或者根据内容转换类型。 总结:确定正确的库,提供示例代码,解释步骤,并指出可能需要注意的地方,比如库的安装、编译选项等。</think>在C++中使用OpenXLSX读取Excel数据并存入数组的实现步骤如下: ### 一、环境配置 1. 安装OpenXLSX库(需使用支持C++的版本,推荐基于GitHub的XLSXIO库) 2. 配置编译环境:添加头文件路径`#include <xlsxio_read.h>`,链接`-lxlsxio_read`库 ### 二、示例代码 ```cpp #include <iostream> #include <vector> #include <xlsxio_read.h> int main() { // 创建二维数组存储数据 std::vector<std::vector<std::string>> dataArray; // 打开Excel文件 xlsxioreader xlsxioread = xlsxioread_open("demo.xlsx"); if (xlsxioread) { // 读取第一个工作表 xlsxioreadersheet sheet = xlsxioread_sheet_open(xlsxioread, NULL, XLSXIOREAD_SKIP_EMPTY_ROWS); if (sheet) { char* value; // 逐行读取数据 while (xlsxioread_sheet_next_row(sheet)) { std::vector<std::string> rowData; // 逐列读取单元格 while ((value = xlsxioread_sheet_next_cell(sheet)) != NULL) { rowData.push_back(value); free(value); } dataArray.push_back(rowData); } xlsxioread_sheet_close(sheet); } xlsxioread_close(xlsxioread); } // 输出验证 for (const auto& row : dataArray) { for (const auto& cell : row) { std::cout << cell << "\t"; } std::cout << std::endl; } return 0; } ``` ### 三、关键点解析 1. **数据存储结构**:使用`std::vector<std::vector<std::string>>`实现动态二维数组存储 2. **内存管理**:每次读取单元格后需调用`free(value)`释放内存[^2] 3. **异常处理**:通过检查`xlsxioread`和`sheet`指针确保文件正确打开 4. **性能优化**:`XLSXIOREAD_SKIP_EMPTY_ROWS`参数跳过空行提升读取效率 ### 四、替代方案对比 | 库名称 | 优点 | 缺点 | |-----------|-----------------------|-----------------------| | libxls | 轻量级,支持旧格式 | 停止维护,不支持xlsx | | OpenXLSX | 纯C++实现 | 文档较少 | | xlnt | 现代C++ API | 依赖Boost库 | | Qt Xlsx | 跨平台,图形界面友好 | 需要Qt框架支持 | ### 五、扩展应用 该方案可与引用[1]的Python写入操作结合,实现C++读取数据处理→Python写入的混合编程工作流。类似引用[4]的密码验证逻辑,可增加数据有效性检查模块。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值