C语言从excel中读取数据放入二维数组
时间: 2023-10-01 17:06:57 浏览: 253
好的,这是一个比较常见的需求,主要利用C语言的文件读写和字符串处理函数来实现。以下是一种可能的实现方式:
1. 打开Excel文件,读取需要的单元格数据并将其保存到文件中
```c
#include <stdio.h>
#define MAX_ROWS 100
#define MAX_COLS 100
int main() {
FILE *fp;
char buffer[1024];
int row, col = 0;
double data[MAX_ROWS][MAX_COLS];
fp = fopen("data.csv", "r");
while(fgets(buffer, 1024, fp)) {
char *ptr = strtok(buffer, ",");
col = 0;
while(ptr != NULL) {
data[row][col] = atof(ptr);
col += 1;
ptr = strtok(NULL, ",");
}
row += 1;
}
fclose(fp);
// Do something with the data
return 0;
}
```
2. 将读取到的数据保存到二维数组中
```c
// Assume the data is stored in data.csv file in the following format:
// 1,2,3,4
// 5,6,7,8
// 9,10,11,12
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define MAX_ROWS 100
#define MAX_COLS 100
int main() {
FILE *fp;
char buffer[1024];
int row, col = 0;
double data[MAX_ROWS][MAX_COLS];
fp = fopen("data.csv", "r");
while(fgets(buffer, 1024, fp)) {
char *ptr = strtok(buffer, ",");
col = 0;
while(ptr != NULL) {
data[row][col] = atof(ptr);
col += 1;
ptr = strtok(NULL, ",");
}
row += 1;
}
fclose(fp);
// Do something with the data
return 0;
}
```
这样,我们就成功地将Excel文件中的数据读取到了二维数组中。
阅读全文