C++ Excel文件讀寫之簡便方法

 對於 文件的 讀寫, 當然是 文本文件 最好讀,最好寫,沒有 什麼文件結構 需要考慮。

 對於windows 下的 excel 等文件 進行操作時就不是那麼容易了,大家可以搜搜 ,基本上都是都複雜的方式才能讀寫

關鍵:

      CSV 格式的文件,是一種文本文件,可以通過 C++ 的文件流簡單的讀寫。  但是這種格式的文本文件,卻是可以有 excel 默認支持的,所以用 excel 打開就是 excel文件。

代碼如下;

[cpp] view plain copy
 
  1. #include <fstream>   
  2. #include <string>  
  3. #include <iostream>  
  4. #include <streambuf>   
  5. using namespace std;   
  6.   
  7. int main()   
  8. {           
  9.     //定義文件輸出流   
  10.     ofstream oFile;   
  11.   
  12.     //打開要輸出的文件   
  13.     oFile.open("scoresheet.csv", ios::out | ios::trunc);    // 這樣就很容易的輸出一個需要的excel 文件  
  14.     oFile << "姓名" << "," << "年齡" << "," << "班級" << "," << "班主任" << endl;   
  15.     oFile << "張三" << "," << "22" << "," << "1" << "," << "JIM" << endl;   
  16.     oFile << "李四" << "," << "23" << "," << "3" << "," << "TOM" << endl;   
  17.   
  18.     oFile.close();   
  19.       
  20.            
  21.     //打開要輸出的文件   
  22.     ifstream iFile("scoresheet.csv");  
  23.     string   readStr((std::istreambuf_iterator<char>(iFile)),  std::istreambuf_iterator<char>());   
  24.      cout <<  readStr.c_str();  
  25.   
  26.       return 0;  

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章