• qt实现sqlite数据库文件与csv文件相互转换


    一、使用场景

            假设一:目前有一个项目记录数据是采用sqlite文件存储的,数据量很大,里面的记录数据客户需要将其导入到execl中进行报表编辑及汇报工作;

            假设二:用户手里有点表配置表格,需要导入到工程的sqlite配置文件中给应用程序使用,配量很大。

    二、实现设计

            在sqlite数据库文件读写方面,基于QT插件库提供的QSQLiteDriverPlugin实现数据库打开、读写、查询等操作。

            

    1. bool executeSQL(QSqlDatabase db,QString _sql)
    2. {
    3. QSqlQuery query(db);
    4. return query.exec(_sql);
    5. };
    6. bool checkTable(QSqlDatabase db, QString _table)
    7. {
    8. QString _sql = QString("select count(*) from sqlite_master where type='table' and name='%1'").arg(_table);
    9. QSqlQuery query(db);
    10. query.exec(_sql);
    11. bool _existTable = true;
    12. if (query.next())
    13. {
    14. int _countTable = query.value(0).toInt();
    15. if (1!=_countTable)
    16. {
    17. _existTable = false;
    18. }
    19. }else{
    20. _existTable = false;
    21. }
    22. return _existTable;
    23. };
    24. bool opendb(QSqlDatabase &db, QString _dbn,QString _dbLink)
    25. {
    26. QString dbv = "QSQLITE";
    27. // QString _dbLink = "db_sqlite_record";
    28. if (QSqlDatabase::contains(_dbLink))
    29. {
    30. db = QSqlDatabase::database(_dbLink);
    31. }else{
    32. db = QSqlDatabase::addDatabase(dbv,_dbLink);
    33. }
    34. // checkDBLink(_dbLink);
    35. // db = QSqlDatabase::addDatabase(dbv,_dbLink);
    36. db.setDatabaseName(_dbn);
    37. if (db.open())
    38. {
    39. return true;
    40. }else{
    41. qDebug() << "open db failed!"<< "---"<< db.lastError().text()<<" \n";
    42. return false;
    43. }
    44. };
    45. bool checkdb_etconf(QSqlDatabase &db, QString _dbn)
    46. {
    47. if (!opendb(db,_dbn,"db_sqlite_etconf"))
    48. {
    49. return false;
    50. }else{
    51. if(!executeSQL(db,"PRAGMA synchronous = OFF"))
    52. {
    53. qDebug() << db.lastError() << "\n";
    54. }
    55. }
    56. //注意,这里进行表过滤,只获取我们需要的表格
    57. if(!checkTable(db,"s101yc"))
    58. {
    59. return false;
    60. }
    61. if(!checkTable(db,"s101yx"))
    62. {
    63. return false;
    64. }
    65. if(!checkTable(db,"s101yk"))
    66. {
    67. return false;
    68. }
    69. if(!checkTable(db,"s101yt"))
    70. {
    71. return false;
    72. }
    73. return true;
    74. };

            在针对csv(XLS 工作表)的文件读写方面,是基于QFile实现的FileQt类封装实现csv文件的有序读取、写入等操作。同时支持直接的.xls文件操作.

    1. //QString _div为csv文件中每行的分割符,QVector > &_lists为读取的数据信息,采用二元数组存储行、列数据
    2. bool readToVector(QString _file,QVector > &_lists, QString _div)
    3. {
    4. QFile file(_file);
    5. if (!file.open(QFile::ReadOnly)) {
    6. qDebug() << "conn't open file " << _file << "!\n";
    7. return false;
    8. }else{
    9. QTextStream stream( &file );
    10. QString line;
    11. while ( !stream.atEnd() ) {
    12. line = stream.readLine();
    13. QStringList _strL = line.split(QRegExp(_div));
    14. // QStringList _strL = line.split(QRegExp(_div),QString::SkipEmptyParts);
    15. QVector _onev;
    16. for (int i = 0; i < _strL.size(); i++)
    17. {
    18. _onev.push_back(_strL[i]);
    19. }
    20. _lists.push_back(_onev);
    21. }
    22. file.close();
    23. if (_lists.empty())
    24. {
    25. return false;
    26. }else{
    27. return true;
    28. }
    29. }
    30. }
    31. bool writeListInfo(QVector list,const QString path,bool appendf)
    32. {
    33. QFile f(path);
    34. if(!f.open(QFile::WriteOnly | QFile::Text | (appendf?QFile::Append:QFile::Truncate)))
    35. return false;
    36. QTextStream out(&f);
    37. // out.setCodec("UTF-8"); //中文编码
    38. for (int i = 0; i < list.size(); i++)
    39. {
    40. out << QString(list[i]);
    41. }
    42. f.close();
    43. return true;
    44. };
    45. /*
    46. *这类函数的意义主要是csv文件里面只有数据,转存到sqlite数据文件中,需要构建表格,就是需要指定表格
    47. *的表名、列名,表名采用csv文件名来表示,列名需要额外指定,本文直接硬代码实现,当然也可以在csv文件
    48. *里面的第一列增加列名,在程序处理时先读取第一列,进行列名命名,在进行转换导入。
    49. */
    50. void inYx(QSqlDatabase &db,QString _path)
    51. {
    52. QVector > _lists;
    53. readToVector(_path,_lists,",");
    54. QSqlQuery query(db);
    55. query.exec("DELETE FROM s101yx");
    56. QVariantList indexids;
    57. QVariantList devids;
    58. QVariantList names;
    59. QVariantList localaddrs;
    60. QVariantList nots;
    61. QVariantList sampdevids;
    62. QVariantList sampaddrs;
    63. QVariantList nametomsts;
    64. int _count = 0;
    65. QString _sql = "INSERT INTO s101yx (INDEXID,DEVID,NAME,LOCALADDR,\"NOT\",SAMPDEVID,SAMPADDR,NAMETOMST) "
    66. "VALUES (?,?,?,?,?,?,?,?)";
    67. for (int i = 0; i < _lists.size(); i++)
    68. {
    69. if (8!=_lists[i].size())
    70. {
    71. continue;
    72. }
    73. indexids << _lists[i][0].toInt();
    74. devids << _lists[i][1].toInt();
    75. names << _lists[i][2];
    76. // names << QString("%1").arg(_lists[i][2].toAscii().data());
    77. localaddrs << _lists[i][3].toInt();
    78. nots << _lists[i][4].toInt();
    79. sampdevids << _lists[i][5].toInt();
    80. sampaddrs << _lists[i][6].toInt();
    81. nametomsts << _lists[i][7];
    82. // nametomsts << QString("%1").arg(_lists[i][7].toAscii().data());
    83. _count+=1;
    84. if (_count>=200||(i==(_lists.size()-1)))
    85. {
    86. try{
    87. query.prepare(_sql);
    88. query.addBindValue(indexids);
    89. query.addBindValue(devids);
    90. query.addBindValue(names);
    91. query.addBindValue(localaddrs);
    92. query.addBindValue(nots);
    93. query.addBindValue(sampdevids);
    94. query.addBindValue(sampaddrs);
    95. query.addBindValue(nametomsts);
    96. if (!query.execBatch())
    97. {
    98. qDebug() << query.lastError();
    99. }
    100. }catch(...){
    101. qDebug() << query.lastError();
    102. }
    103. indexids.clear();
    104. devids.clear();
    105. names.clear();
    106. localaddrs.clear();
    107. nots.clear();
    108. sampdevids.clear();
    109. sampaddrs.clear();
    110. nametomsts.clear();
    111. _count = 0;
    112. }
    113. }
    114. };
    115. ...

            提供一个简要对话框设置数据库文件路径及csv文件路径,提供转换选择按钮实现文件数据转换输出。

    1. void InOrOutConf::DBToCsv()
    2. {
    3. QString _dbn = this->pathEdit->text();
    4. QFile _file(_dbn);
    5. if (!_file.exists())
    6. {
    7. warLabel->setText("db isn't exist!");
    8. return;
    9. }
    10. // s101yc * ycs = new s101yc[10];
    11. // int ret = GetS101yc(_dbn.toStdString().c_str(),"",ycs,10);
    12. // if(ret>0){
    13. // for (int i = 0; i < ret; i++)
    14. // {
    15. // qDebug() << QString("%1").arg(ycs[i].NAME)<<"\n";
    16. // qDebug() << QString("%1").arg(G2U(ycs[i].NAME))<<"\n";
    17. // qDebug() << QString("%1").arg(U2G(ycs[i].NAME))<<"\n";
    18. // qDebug() << QString("%1").arg(ASCII2UTF_8(std::string(ycs[i].NAME)).c_str())<<"\n";
    19. // qDebug() << QString("%1").arg(UTF_82ASCII(std::string(ycs[i].NAME)).c_str())<<"\n";
    20. // }
    21. // }
    22. QSqlDatabase db;
    23. if(!checkdb_etconf(db,_dbn))
    24. {
    25. warLabel->setText("db isn't table we need!");
    26. return;
    27. }
    28. warLabel->setText("db to csv runing!");
    29. //这里本应通过读取表名(或配置实现)+路径来命名csv文件路径的,本案例测试时,强行指定文件名
    30. outYc(db,this->dirEdit->text()+divPath+"s101yc.csv");
    31. outYx(db,this->dirEdit->text()+divPath+"s101yx.csv");
    32. outYk(db,this->dirEdit->text()+divPath+"s101yk.csv");
    33. outYt(db,this->dirEdit->text()+divPath+"s101yt.csv");
    34. warLabel->setText("db to csv finish!");
    35. db.close();
    36. };
    37. void InOrOutConf::scvToDB()
    38. {
    39. QString _dbn = this->pathEdit->text();
    40. QFile _file(_dbn);
    41. if (!_file.exists())
    42. {
    43. warLabel->setText("db isn't exist!");
    44. return;
    45. }
    46. QSqlDatabase db;
    47. if(!checkdb_etconf(db,_dbn))
    48. {
    49. warLabel->setText("db isn't table we need!");
    50. return;
    51. }
    52. warLabel->setText("csv to db runing!");
    53. //这里本应通过配置定义+路径来读取csv文件,本案例测试时,强行指定文件名
    54. inYc(db,this->dirEdit->text()+divPath+"s101yc.csv");
    55. inYx(db,this->dirEdit->text()+divPath+"s101yx.csv");
    56. inYk(db,this->dirEdit->text()+divPath+"s101yk.csv");
    57. inYt(db,this->dirEdit->text()+divPath+"s101yt.csv");
    58. warLabel->setText("csv to db finish!");
    59. db.close();
    60. };

      三、工程实现

            本文采用qt5.8来实现的,并对该版本进行了静态编译,win系统是win10-64bit,linux系统是centos7-64bit系统,同时静态编译了plugins\\sqldrivers插件。

            整个工程目录结构如下:

    1. sqlite_and_csv_trans
    2. bin
    3. file
    4. FileQt.h
    5. FileQt.cpp
    6. myfiledialog.h
    7. myfiledialog.cpp
    8. strcode.hpp
    9. strcode.cpp
    10. languages
    11. dbInOrOut_cn.qm
    12. dbInOrOut_cn.ts
    13. view
    14. inOrOutConf.h
    15. inOrOutConf.cpp
    16. dbInOrOut.qrc
    17. dbIntOrOut.pro
    18. main.cpp

     dbIntOrOut.pro:

    1. QT += core
    2. QT += gui
    3. QT += sql
    4. greaterThan(QT_MAJOR_VERSION, 4) {
    5. QT += printsupport
    6. QT += concurrent
    7. QT += widgets
    8. }
    9. TEMPLATE = app
    10. DESTDIR = bin
    11. CONFIG += qt warn_on debug_and_release
    12. CONFIG += static
    13. CONFIG(debug, debug|release) {
    14. TARGET = dbInOrOutd
    15. OBJECTS_DIR = debug/obj
    16. MOC_DIR = debug/moc
    17. CONFIG += console
    18. DEFINES += _DEBUG
    19. }else{
    20. TARGET = dbInOrOut
    21. OBJECTS_DIR = release/obj
    22. MOC_DIR = release/moc
    23. DEFINES += NODEBUG
    24. }
    25. DEFINES += QTWIN_32 \
    26. QT_CORE_LIB \
    27. QT_GUI_LIB \
    28. QT_SQL_LIB \
    29. QT_THREAD_SUPPORT
    30. #请指定qt的sqlite插件路径
    31. QT_SQL = D:\\workForSoftware\\Qt\\Qt5.8.0\\5.8\\msvc2015_64_static\\plugins\\sqldrivers
    32. win32{
    33. CONFIG(debug, debug|release) {
    34. LIBS += $$(QT_SQL)\\qsqlited.lib
    35. } else {
    36. LIBS += $$(QT_SQL)\\qsqlite.lib
    37. }
    38. }
    39. HEADERS += view/inOrOutConf.h \
    40. file/myfiledialog.h \
    41. file/strcode.hpp \
    42. SOURCES += main.cpp\
    43. view/inOrOutConf.cpp \
    44. file/myfiledialog.cpp \
    45. file/strcode.cpp \
    46. TRANSLATIONS += languages/dbInOrOut_cn.ts
    47. RESOURCES += dbInOrOut.qrc

    dbInOrOut.qrc

    1. "1.0">
    2. "/">
    3. languages/dbInOrOut_cn.qm

    strcode.hpp,实现字符编码转换

    1. #if _MSC_VER > 1000
    2. #pragma once
    3. #endif // _MSC_VER > 1000
    4. #ifndef STRCODE_HPP
    5. #define STRCODE_HPP
    6. #include
    7. #ifdef WIN32
    8. #include
    9. #endif
    10. #ifdef __linux__
    11. int code_convert(char *from_charset,char *to_charset,char *inbuf,size_t inlen,char *outbuf,size_t outlen);
    12. int u2g(char *inbuf,int inlen,char *outbuf,int outlen);
    13. int g2u(char *inbuf,size_t inlen,char *outbuf,size_t outlen);
    14. int u2a(char *inbuf,int inlen,char *outbuf,int outlen);
    15. int a2u(char *inbuf,int inlen,char *outbuf,int outlen);
    16. #endif
    17. #ifdef WIN32
    18. std::wstring Utf82Unicode(const std::string& utf8string);
    19. std::string WideByte2Acsi(std::wstring& wstrcode);
    20. std::wstring Acsi2WideByte(std::string& strascii);
    21. std::string Unicode2Utf8(const std::wstring& widestring);
    22. #endif
    23. bool UnicodeToAnsi(wchar_t* lpString,char* szAnsi);//(in,out)
    24. bool AnsiToUnicode(char* lpString,wchar_t* szUnicode);//(in,out)
    25. char* U2G(const char* utf8);
    26. char* G2U(const char* gb2312);
    27. std::string UTF_82ASCII(std::string &strUtf8Code);
    28. std::string ASCII2UTF_8(std::string& strAsciiCode);
    29. //using namespace std;
    30. bool containStr(std::string _str, std::string _strsub);
    31. int enc_unicode_to_utf8_one(unsigned long unic, unsigned char *pOutput, int outSize);
    32. // int enc_utf8_to_unicode_one(const unsigned char* pInput, unsigned long *Unic);
    33. //
    34. /*
    35. std::string ws2s(const std::wstring& ws);
    36. std::wstring s2ws(const std::string& s);
    37. std::wstring UTF2Uni(const char* src, std::wstring &t);
    38. int Uni2UTF( const std::wstring& strRes, char *utf8, int nMaxSize );
    39. std::string s2utfs(const std::string& strSrc);
    40. std::string utfs2s(const std::string& strutf);
    41. */
    42. #endif //STRCODE_HPP

    strcode.cpp

    1. #include "strcode.hpp"
    2. #include
    3. #include
    4. #include
    5. #include
    6. #include
    7. #include
    8. #include
    9. #ifdef __linux__
    10. #include
    11. #endif
    12. #ifdef __linux__
    13. //代码转换:从一种编码转为另一种编码
    14. int code_convert(char *from_charset,char *to_charset,char *inbuf,size_t inlen,char *outbuf,size_t outlen)
    15. {
    16. iconv_t cd;
    17. int rc;
    18. char **pin = &inbuf;
    19. char **pout = &outbuf;
    20. cd = iconv_open(to_charset,from_charset);
    21. if (cd==0) return -1;
    22. memset(outbuf,0,outlen);
    23. if (iconv(cd,pin,&inlen,pout,&outlen)==-1) return -1;
    24. iconv_close(cd);
    25. return 0;
    26. }
    27. //UNICODE码转为GB2312码
    28. int u2g(char *inbuf,int inlen,char *outbuf,int outlen)
    29. {
    30. return code_convert("utf-8","gb2312",inbuf,inlen,outbuf,outlen);
    31. }
    32. //GB2312码转为UNICODE码
    33. int g2u(char *inbuf,size_t inlen,char *outbuf,size_t outlen)
    34. {
    35. return code_convert("gb2312","utf-8",inbuf,inlen,outbuf,outlen);
    36. }
    37. int u2a(char *inbuf,int inlen,char *outbuf,int outlen)
    38. {
    39. return code_convert("utf-8","ascii",inbuf,inlen,outbuf,outlen);
    40. }
    41. int a2u(char *inbuf,int inlen,char *outbuf,int outlen)
    42. {
    43. return code_convert("ascii","utf-8",inbuf,inlen,outbuf,outlen);
    44. }
    45. #endif
    46. #ifdef WIN32
    47. //UTF-8¡ÁaUnicode
    48. std::wstring Utf82Unicode(const std::string& utf8string)
    49. {
    50. int widesize = ::MultiByteToWideChar(CP_UTF8, 0, utf8string.c_str(), -1, NULL, 0);
    51. if (widesize == ERROR_NO_UNICODE_TRANSLATION)
    52. {
    53. throw std::exception("Invalid UTF-8 sequence.");
    54. }
    55. if (widesize == 0)
    56. {
    57. throw std::exception("Error in conversion.");
    58. }
    59. std::vector<wchar_t> resultstring(widesize);
    60. int convresult = ::MultiByteToWideChar(CP_UTF8, 0, utf8string.c_str(), -1, &resultstring[0], widesize);
    61. if (convresult != widesize)
    62. {
    63. throw std::exception("La falla!");
    64. }
    65. return std::wstring(&resultstring[0]);
    66. };
    67. //unicode ¡Áa?a ascii
    68. std::string WideByte2Acsi(std::wstring& wstrcode)
    69. {
    70. int asciisize = ::WideCharToMultiByte(CP_OEMCP, 0, wstrcode.c_str(), -1, NULL, 0, NULL, NULL);
    71. if (asciisize == ERROR_NO_UNICODE_TRANSLATION)
    72. {
    73. throw std::exception("Invalid UTF-8 sequence.");
    74. }
    75. if (asciisize == 0)
    76. {
    77. throw std::exception("Error in conversion.");
    78. }
    79. std::vector<char> resultstring(asciisize);
    80. int convresult =::WideCharToMultiByte(CP_OEMCP, 0, wstrcode.c_str(), -1, &resultstring[0], asciisize, NULL, NULL);
    81. if (convresult != asciisize)
    82. {
    83. throw std::exception("La falla!");
    84. }
    85. return std::string(&resultstring[0]);
    86. };
    87. ///
    88. //ascii ¡Áa Unicode
    89. std::wstring Acsi2WideByte(std::string& strascii)
    90. {
    91. int widesize = MultiByteToWideChar (CP_ACP, 0, (char*)strascii.c_str(), -1, NULL, 0);
    92. if (widesize == ERROR_NO_UNICODE_TRANSLATION)
    93. {
    94. throw std::exception("Invalid UTF-8 sequence.");
    95. }
    96. if (widesize == 0)
    97. {
    98. throw std::exception("Error in conversion.");
    99. }
    100. std::vector<wchar_t> resultstring(widesize);
    101. int convresult = MultiByteToWideChar (CP_ACP, 0, (char*)strascii.c_str(), -1, &resultstring[0], widesize);
    102. if (convresult != widesize)
    103. {
    104. throw std::exception("La falla!");
    105. }
    106. return std::wstring(&resultstring[0]);
    107. };
    108. //Unicode ¡Áa Utf8
    109. std::string Unicode2Utf8(const std::wstring& widestring)
    110. {
    111. int utf8size = ::WideCharToMultiByte(CP_UTF8, 0, widestring.c_str(), -1, NULL, 0, NULL, NULL);
    112. if (utf8size == 0)
    113. {
    114. throw std::exception("Error in conversion.");
    115. }
    116. std::vector<char> resultstring(utf8size);
    117. int convresult = ::WideCharToMultiByte(CP_UTF8, 0, widestring.c_str(), -1, &resultstring[0], utf8size, NULL, NULL);
    118. if (convresult != utf8size)
    119. {
    120. throw std::exception("La falla!");
    121. }
    122. return std::string(&resultstring[0]);
    123. };
    124. #endif
    125. //mbstowcs()函数和wcstombs()函数,选自CRT库。平台无关,但需设定local。不设定Local,中文会乱码
    126. bool UnicodeToAnsi(wchar_t* lpString,char* szAnsi)//(in,out)
    127. {
    128. size_t nLen=wcslen(lpString)*2;//wcslen
    129. char* lpszBuf=(char*)malloc(nLen);//malloc and
    130. setlocale(LC_ALL,"");
    131. size_t nRet=wcstombs(lpszBuf,lpString,nLen);//wcstombs
    132. if(nRet<0)
    133. {
    134. free(lpszBuf);
    135. return false;
    136. }
    137. strcpy(szAnsi,lpszBuf);
    138. return true;
    139. };
    140. bool AnsiToUnicode(char* lpString,wchar_t* szUnicode)//(in,out)
    141. {
    142. size_t nLen=strlen(lpString);
    143. wchar_t* lpszBuf=(wchar_t*)malloc(nLen);//malloc and
    144. setlocale(LC_ALL,"");
    145. size_t nRet = mbstowcs(lpszBuf, lpString, nLen);
    146. if(nRet<0)
    147. {
    148. free(lpszBuf);
    149. return false;
    150. }
    151. wcscpy(szUnicode,lpszBuf);
    152. return true;
    153. };
    154. //UTF-8到GB2312的转换
    155. char* U2G(const char* utf8){
    156. static char szRet[1024];
    157. memset( szRet, 0x00, 1024);
    158. int len = MultiByteToWideChar(CP_UTF8, 0, utf8, -1, NULL, 0);
    159. wchar_t* wstr = new wchar_t[len+1];
    160. memset(wstr, 0, len+1);
    161. MultiByteToWideChar(CP_UTF8, 0, utf8, -1, wstr, len);
    162. len = WideCharToMultiByte(CP_ACP, 0, wstr, -1, NULL, 0, NULL, NULL);
    163. WideCharToMultiByte(CP_ACP, 0, wstr, -1, szRet, len, NULL, NULL);
    164. if(wstr) delete[] wstr;
    165. return szRet;
    166. };
    167. //GB2312到UTF-8的转换
    168. char* G2U(const char* gb2312){
    169. static char szRet[1024];
    170. memset( szRet,0x00,1024 );
    171. int len = MultiByteToWideChar(CP_ACP, 0, gb2312, -1, NULL, 0);
    172. wchar_t* wstr = new wchar_t[len+1];
    173. memset(wstr, 0, len+1);
    174. MultiByteToWideChar(CP_ACP, 0, gb2312, -1, wstr, len);
    175. len = WideCharToMultiByte(CP_UTF8, 0, wstr, -1, NULL, 0, NULL, NULL);
    176. WideCharToMultiByte(CP_UTF8, 0, wstr, -1, szRet, len, NULL, NULL);
    177. if(wstr) delete[] wstr;
    178. return szRet;
    179. };
    180. std::string UTF_82ASCII(std::string &strUtf8Code)
    181. {
    182. #ifdef WIN32
    183. std::string strRet("");
    184. //?¨¨¡ã? utf8 ¡Áa?a unicode
    185. std::wstring wstr = Utf82Unicode(strUtf8Code);
    186. //¡Á?o¨®¡ã? unicode ¡Áa?a ascii
    187. strRet = WideByte2Acsi(wstr);
    188. return strRet;
    189. #endif
    190. #ifdef linux
    191. char lpszBuf[256]={0};
    192. u2a(const_cast<char*>(strUtf8Code.c_str()),strUtf8Code.size(),lpszBuf,256);
    193. return std::string(lpszBuf);
    194. #endif
    195. };
    196. //ascii ¡Áa Utf8
    197. std::string ASCII2UTF_8(std::string& strAsciiCode)
    198. {
    199. #ifdef WIN32
    200. std::string strRet("");
    201. //?¨¨¡ã? ascii ¡Áa?a unicode
    202. std::wstring wstr = Acsi2WideByte(strAsciiCode);
    203. //¡Á?o¨®¡ã? unicode ¡Áa?a utf8
    204. strRet = Unicode2Utf8(wstr);
    205. return strRet;
    206. #endif
    207. #ifdef linux
    208. char lpszBuf[256]={0};
    209. a2u(const_cast<char*>(strAsciiCode.c_str()),strAsciiCode.size(),lpszBuf,256);
    210. return std::string(lpszBuf);
    211. #endif
    212. };
    213. /
    214. bool containStr(std::string _str, std::string _strsub)
    215. {
    216. std::string::size_type pos = _str.find(_strsub);//²éÕÒ_strsub±êʶ
    217. if(pos!=std::string::npos){
    218. return true;
    219. }
    220. return false;
    221. };
    222. /
    223. /*****************************************************************************
    224. * 将一个字符的Unicode(UCS-2和UCS-4)编码转换成UTF-8编码.
    225. *
    226. * 参数:
    227. * unic 字符的Unicode编码值
    228. * pOutput 指向输出的用于存储UTF8编码值的缓冲区的指针
    229. * outsize pOutput缓冲的大小
    230. *
    231. * 返回值:
    232. * 返回转换后的字符的UTF8编码所占的字节数, 如果出错则返回 0 .
    233. *
    234. * 注意:
    235. * 1. UTF8没有字节序问题, 但是Unicode有字节序要求;
    236. * 字节序分为大端(Big Endian)和小端(Little Endian)两种;
    237. * 在Intel处理器中采用小端法表示, 在此采用小端法表示. (低地址存低位)
    238. * 2. 请保证 pOutput 缓冲区有最少有 6 字节的空间大小!
    239. ****************************************************************************/
    240. int enc_unicode_to_utf8_one(unsigned long unic, unsigned char *pOutput, int outSize)
    241. {
    242. assert(pOutput != NULL);
    243. assert(outSize >= 6);
    244. if ( unic <= 0x0000007F )
    245. {
    246. // * U-00000000 - U-0000007F: 0xxxxxxx
    247. *pOutput = (unic & 0x7F);
    248. return 1;
    249. }
    250. else if ( unic >= 0x00000080 && unic <= 0x000007FF )
    251. {
    252. // * U-00000080 - U-000007FF: 110xxxxx 10xxxxxx
    253. *(pOutput+1) = (unic & 0x3F) | 0x80;
    254. *pOutput = ((unic >> 6) & 0x1F) | 0xC0;
    255. return 2;
    256. }
    257. else if ( unic >= 0x00000800 && unic <= 0x0000FFFF )
    258. {
    259. // * U-00000800 - U-0000FFFF: 1110xxxx 10xxxxxx 10xxxxxx
    260. *(pOutput+2) = (unic & 0x3F) | 0x80;
    261. *(pOutput+1) = ((unic >> 6) & 0x3F) | 0x80;
    262. *pOutput = ((unic >> 12) & 0x0F) | 0xE0;
    263. return 3;
    264. }
    265. else if ( unic >= 0x00010000 && unic <= 0x001FFFFF )
    266. {
    267. // * U-00010000 - U-001FFFFF: 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
    268. *(pOutput+3) = (unic & 0x3F) | 0x80;
    269. *(pOutput+2) = ((unic >> 6) & 0x3F) | 0x80;
    270. *(pOutput+1) = ((unic >> 12) & 0x3F) | 0x80;
    271. *pOutput = ((unic >> 18) & 0x07) | 0xF0;
    272. return 4;
    273. }
    274. else if ( unic >= 0x00200000 && unic <= 0x03FFFFFF )
    275. {
    276. // * U-00200000 - U-03FFFFFF: 111110xx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx
    277. *(pOutput+4) = (unic & 0x3F) | 0x80;
    278. *(pOutput+3) = ((unic >> 6) & 0x3F) | 0x80;
    279. *(pOutput+2) = ((unic >> 12) & 0x3F) | 0x80;
    280. *(pOutput+1) = ((unic >> 18) & 0x3F) | 0x80;
    281. *pOutput = ((unic >> 24) & 0x03) | 0xF8;
    282. return 5;
    283. }
    284. else if ( unic >= 0x04000000 && unic <= 0x7FFFFFFF )
    285. {
    286. // * U-04000000 - U-7FFFFFFF: 1111110x 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx
    287. *(pOutput+5) = (unic & 0x3F) | 0x80;
    288. *(pOutput+4) = ((unic >> 6) & 0x3F) | 0x80;
    289. *(pOutput+3) = ((unic >> 12) & 0x3F) | 0x80;
    290. *(pOutput+2) = ((unic >> 18) & 0x3F) | 0x80;
    291. *(pOutput+1) = ((unic >> 24) & 0x3F) | 0x80;
    292. *pOutput = ((unic >> 30) & 0x01) | 0xFC;
    293. return 6;
    294. }
    295. return 0;
    296. }
    297. /*****************************************************************************
    298. * 将一个字符的UTF8编码转换成Unicode(UCS-2和UCS-4)编码.
    299. *
    300. * 参数:
    301. * pInput 指向输入缓冲区, 以UTF-8编码
    302. * Unic 指向输出缓冲区, 其保存的数据即是Unicode编码值,
    303. * 类型为unsigned long .
    304. *
    305. * 返回值:
    306. * 成功则返回该字符的UTF8编码所占用的字节数; 失败则返回0.
    307. *
    308. * 注意:
    309. * 1. UTF8没有字节序问题, 但是Unicode有字节序要求;
    310. * 字节序分为大端(Big Endian)和小端(Little Endian)两种;
    311. * 在Intel处理器中采用小端法表示, 在此采用小端法表示. (低地址存低位)
    312. ****************************************************************************/
    313. /*
    314. int enc_utf8_to_unicode_one(const unsigned char* pInput, unsigned long *Unic)
    315. {
    316. assert(pInput != NULL && Unic != NULL);
    317. // b1 表示UTF-8编码的pInput中的高字节, b2 表示次高字节, ...
    318. char b1, b2, b3, b4, b5, b6;
    319. *Unic = 0x0; // 把 *Unic 初始化为全零
    320. int utfbytes = enc_get_utf8_size(*pInput);
    321. unsigned char *pOutput = (unsigned char *) Unic;
    322. switch ( utfbytes )
    323. {
    324. case 0:
    325. *pOutput = *pInput;
    326. utfbytes += 1;
    327. break;
    328. case 2:
    329. b1 = *pInput;
    330. b2 = *(pInput + 1);
    331. if ( (b2 & 0xE0) != 0x80 )
    332. return 0;
    333. *pOutput = (b1 << 6) + (b2 & 0x3F);
    334. *(pOutput+1) = (b1 >> 2) & 0x07;
    335. break;
    336. case 3:
    337. b1 = *pInput;
    338. b2 = *(pInput + 1);
    339. b3 = *(pInput + 2);
    340. if ( ((b2 & 0xC0) != 0x80) || ((b3 & 0xC0) != 0x80) )
    341. return 0;
    342. *pOutput = (b2 << 6) + (b3 & 0x3F);
    343. *(pOutput+1) = (b1 << 4) + ((b2 >> 2) & 0x0F);
    344. break;
    345. case 4:
    346. b1 = *pInput;
    347. b2 = *(pInput + 1);
    348. b3 = *(pInput + 2);
    349. b4 = *(pInput + 3);
    350. if ( ((b2 & 0xC0) != 0x80) || ((b3 & 0xC0) != 0x80)
    351. || ((b4 & 0xC0) != 0x80) )
    352. return 0;
    353. *pOutput = (b3 << 6) + (b4 & 0x3F);
    354. *(pOutput+1) = (b2 << 4) + ((b3 >> 2) & 0x0F);
    355. *(pOutput+2) = ((b1 << 2) & 0x1C) + ((b2 >> 4) & 0x03);
    356. break;
    357. case 5:
    358. b1 = *pInput;
    359. b2 = *(pInput + 1);
    360. b3 = *(pInput + 2);
    361. b4 = *(pInput + 3);
    362. b5 = *(pInput + 4);
    363. if ( ((b2 & 0xC0) != 0x80) || ((b3 & 0xC0) != 0x80)
    364. || ((b4 & 0xC0) != 0x80) || ((b5 & 0xC0) != 0x80) )
    365. return 0;
    366. *pOutput = (b4 << 6) + (b5 & 0x3F);
    367. *(pOutput+1) = (b3 << 4) + ((b4 >> 2) & 0x0F);
    368. *(pOutput+2) = (b2 << 2) + ((b3 >> 4) & 0x03);
    369. *(pOutput+3) = (b1 << 6);
    370. break;
    371. case 6:
    372. b1 = *pInput;
    373. b2 = *(pInput + 1);
    374. b3 = *(pInput + 2);
    375. b4 = *(pInput + 3);
    376. b5 = *(pInput + 4);
    377. b6 = *(pInput + 5);
    378. if ( ((b2 & 0xC0) != 0x80) || ((b3 & 0xC0) != 0x80)
    379. || ((b4 & 0xC0) != 0x80) || ((b5 & 0xC0) != 0x80)
    380. || ((b6 & 0xC0) != 0x80) )
    381. return 0;
    382. *pOutput = (b5 << 6) + (b6 & 0x3F);
    383. *(pOutput+1) = (b5 << 4) + ((b6 >> 2) & 0x0F);
    384. *(pOutput+2) = (b3 << 2) + ((b4 >> 4) & 0x03);
    385. *(pOutput+3) = ((b1 << 6) & 0x40) + (b2 & 0x3F);
    386. break;
    387. default:
    388. return 0;
    389. break;
    390. }
    391. return utfbytes;
    392. }
    393. */
    394. ///
    395. /*
    396. std::string ws2s(const std::wstring& ws)
    397. {
    398. std::string curLocale = setlocale(LC_ALL, NULL); // curLocale = "C";
    399. setlocale(LC_ALL, "chs");
    400. const wchar_t* _Source = ws.c_str();
    401. size_t _Dsize = 2 * ws.size() + 1;
    402. char *_Dest = new char[_Dsize];
    403. memset(_Dest,0,_Dsize);
    404. wcstombs(_Dest,_Source,_Dsize);
    405. std::string result = _Dest;
    406. delete []_Dest;
    407. setlocale(LC_ALL, curLocale.c_str());
    408. return result;
    409. }
    410. */
    411. /*
    412. std::wstring s2ws(const std::string& s)
    413. {
    414. setlocale(LC_ALL, "chs");
    415. const char* _Source = s.c_str();
    416. size_t _Dsize = s.size() + 1;
    417. wchar_t *_Dest = new wchar_t[_Dsize];
    418. wmemset(_Dest, 0, _Dsize);
    419. int nret = mbstowcs(_Dest,_Source,_Dsize);
    420. std::wstring result = _Dest;
    421. delete []_Dest;
    422. setlocale(LC_ALL, "C");
    423. return result;
    424. }
    425. */
    426. /*
    427. std::wstring UTF2Uni(const char* src, std::wstring &t)
    428. {
    429. if (src == NULL)
    430. {
    431. return L"";
    432. }
    433. int size_s = strlen(src);
    434. int size_d = size_s + 10; //?
    435. wchar_t *des = new wchar_t[size_d];
    436. memset(des, 0, size_d * sizeof(wchar_t));
    437. int s = 0, d = 0;
    438. bool toomuchbyte = true; //set true to skip error prefix.
    439. while (s < size_s && d < size_d)
    440. {
    441. unsigned char c = src[s];
    442. if ((c & 0x80) == 0)
    443. {
    444. des[d++] += src[s++];
    445. }
    446. else if((c & 0xE0) == 0xC0) ///< 110x-xxxx 10xx-xxxx
    447. {
    448. WCHAR &wideChar = des[d++];
    449. wideChar = (src[s + 0] & 0x3F) << 6;
    450. wideChar |= (src[s + 1] & 0x3F);
    451. s += 2;
    452. }
    453. else if((c & 0xF0) == 0xE0) ///< 1110-xxxx 10xx-xxxx 10xx-xxxx
    454. {
    455. WCHAR &wideChar = des[d++];
    456. wideChar = (src[s + 0] & 0x1F) << 12;
    457. wideChar |= (src[s + 1] & 0x3F) << 6;
    458. wideChar |= (src[s + 2] & 0x3F);
    459. s += 3;
    460. }
    461. else if((c & 0xF8) == 0xF0) ///< 1111-0xxx 10xx-xxxx 10xx-xxxx 10xx-xxxx
    462. {
    463. WCHAR &wideChar = des[d++];
    464. wideChar = (src[s + 0] & 0x0F) << 18;
    465. wideChar = (src[s + 1] & 0x3F) << 12;
    466. wideChar |= (src[s + 2] & 0x3F) << 6;
    467. wideChar |= (src[s + 3] & 0x3F);
    468. s += 4;
    469. }
    470. else
    471. {
    472. WCHAR &wideChar = des[d++]; ///< 1111-10xx 10xx-xxxx 10xx-xxxx 10xx-xxxx 10xx-xxxx
    473. wideChar = (src[s + 0] & 0x07) << 24;
    474. wideChar = (src[s + 1] & 0x3F) << 18;
    475. wideChar = (src[s + 2] & 0x3F) << 12;
    476. wideChar |= (src[s + 3] & 0x3F) << 6;
    477. wideChar |= (src[s + 4] & 0x3F);
    478. s += 5;
    479. }
    480. }
    481. t = des;
    482. delete[] des;
    483. des = NULL;
    484. return t;
    485. }
    486. */
    487. /*
    488. int Uni2UTF( const std::wstring& strRes, char *utf8, int nMaxSize )
    489. {
    490. if (utf8 == NULL) {
    491. return -1;
    492. }
    493. int len = 0;
    494. int size_d = nMaxSize;
    495. for (std::wstring::const_iterator it = strRes.begin(); it != strRes.end(); ++it)
    496. {
    497. wchar_t wchar = *it;
    498. if (wchar < 0x80)
    499. { //
    500. //length = 1;
    501. utf8[len++] = (char)wchar;
    502. }
    503. else if(wchar < 0x800)
    504. {
    505. //length = 2;
    506. if (len + 1 >= size_d)
    507. return -1;
    508. utf8[len++] = 0xc0 | ( wchar >> 6 );
    509. utf8[len++] = 0x80 | ( wchar & 0x3f );
    510. }
    511. else if(wchar < 0x10000 )
    512. {
    513. //length = 3;
    514. if (len + 2 >= size_d)
    515. return -1;
    516. utf8[len++] = 0xe0 | ( wchar >> 12 );
    517. utf8[len++] = 0x80 | ( (wchar >> 6) & 0x3f );
    518. utf8[len++] = 0x80 | ( wchar & 0x3f );
    519. }
    520. else if( wchar < 0x200000 )
    521. {
    522. //length = 4;
    523. if (len + 3 >= size_d)
    524. return -1;
    525. utf8[len++] = 0xf0 | ( (int)wchar >> 18 );
    526. utf8[len++] = 0x80 | ( (wchar >> 12) & 0x3f );
    527. utf8[len++] = 0x80 | ( (wchar >> 6) & 0x3f );
    528. utf8[len++] = 0x80 | ( wchar & 0x3f );
    529. }
    530. }
    531. return len;
    532. }
    533. */
    534. /*
    535. std::string s2utfs(const std::string& strSrc)
    536. {
    537. std::string strRes;
    538. std::wstring wstrUni = s2ws(strSrc);
    539. char* chUTF8 = new char[wstrUni.length() * 3];
    540. memset(chUTF8,0x00,wstrUni.length() * 3);
    541. Uni2UTF(wstrUni,chUTF8, wstrUni.length() * 3);
    542. strRes = chUTF8;
    543. delete []chUTF8;
    544. return strRes;
    545. }
    546. */
    547. /*
    548. std::string utfs2s(const std::string& strutf)
    549. {
    550. std::wstring wStrTmp;
    551. UTF2Uni( strutf.c_str(),wStrTmp);
    552. return ws2s(wStrTmp);
    553. }
    554. */

    myfiledialog.h基于QFileDialog实现自定义对话框

    1. #ifndef MYFILEDIALOG_H
    2. #define MYFILEDIALOG_H
    3. #include
    4. class MyFileDialog : public QFileDialog
    5. {
    6. Q_OBJECT
    7. public:
    8. MyFileDialog( QWidget * parent = 0
    9. , int _model = 0
    10. , const QString & caption = QString()
    11. , const QString & directory = QString()
    12. , const QString & filter = QString());
    13. ~MyFileDialog();
    14. private:
    15. void init(int _model);
    16. private:
    17. QString initDir;
    18. /* data */
    19. };
    20. #endif //MYFILEDIALOG_H

    myfiledialog.cpp

    1. #include "myfiledialog.h"
    2. #include
    3. MyFileDialog::MyFileDialog(QWidget * parent
    4. , int _model
    5. , const QString & caption
    6. , const QString & directory
    7. , const QString & filter )
    8. : QFileDialog(parent,caption,directory,filter)
    9. , initDir(directory)
    10. {
    11. init(_model);
    12. }
    13. MyFileDialog::~MyFileDialog()
    14. {
    15. }
    16. void MyFileDialog::init(int _model)
    17. {
    18. this->setWindowTitle(tr("File Path Set Dialog"));
    19. this->setLabelText(QFileDialog::LookIn,tr("MyLookIn"));
    20. this->setLabelText(QFileDialog::FileName,tr("MyfileName"));
    21. this->setLabelText(QFileDialog::FileType,tr("MyFileType"));
    22. QString _appDir = QCoreApplication::applicationDirPath();
    23. switch(_model)
    24. {
    25. case 0:
    26. this->setAcceptMode(QFileDialog::AcceptSave);
    27. this->setLabelText(QFileDialog::Accept,tr("mySave"));
    28. this->setDirectory(_appDir);
    29. this->setNameFilter(tr("csv Files (*.csv)"));
    30. break;
    31. case 1:
    32. this->setAcceptMode(QFileDialog::AcceptSave);
    33. this->setLabelText(QFileDialog::Accept,tr("mySave"));
    34. this->setDirectory(_appDir);
    35. this->setNameFilter(tr("xml Files (*.xml)"));
    36. break;
    37. case 2:
    38. this->setAcceptMode(QFileDialog::AcceptOpen);
    39. this->setLabelText(QFileDialog::Accept,tr("myOpen"));
    40. this->setDirectory(_appDir);
    41. this->setNameFilter(tr("xml Files (*.xml)"));
    42. break;
    43. case 3:
    44. {
    45. // this->setAcceptMode(QFileDialog::AcceptOpen);
    46. this->setFilter(QDir::NoDotAndDotDot);
    47. this->setFileMode(QFileDialog::Directory);
    48. this->setOptions(QFileDialog::ReadOnly);
    49. this->setLabelText(QFileDialog::Accept,tr("myChoose"));
    50. }
    51. break;
    52. case 4:
    53. {
    54. this->setAcceptMode(QFileDialog::AcceptOpen);
    55. this->setLabelText(QFileDialog::Accept,tr("myOpen"));
    56. this->setNameFilter(tr("sqlite Files (*.db)"));
    57. }
    58. break;
    59. case 5:
    60. {
    61. this->setAcceptMode(QFileDialog::AcceptOpen);
    62. this->setLabelText(QFileDialog::Accept,tr("myOpen"));
    63. this->setFilter(QDir::Files);
    64. }
    65. break;
    66. case 6:
    67. {
    68. this->setAcceptMode(QFileDialog::AcceptSave);
    69. this->setLabelText(QFileDialog::Accept,tr("mySave"));
    70. this->setNameFilter(tr("csv Files (*.csv)"));
    71. }
    72. case 7:
    73. {
    74. this->setAcceptMode(QFileDialog::AcceptOpen);
    75. this->setLabelText(QFileDialog::Accept,tr("myOpen"));
    76. this->setDirectory(_appDir);
    77. this->setNameFilter(tr("csv Files (*.csv);;"
    78. "ini files (*.ini);;"
    79. "Text files (*.txt);;"
    80. "xml files (*.xml);;"
    81. "Any files (*)"));
    82. }
    83. break;
    84. case 8:
    85. {
    86. this->setAcceptMode(QFileDialog::AcceptOpen);
    87. this->setLabelText(QFileDialog::Accept,tr("myOpen"));
    88. this->setNameFilter(tr("Any files (*)"));
    89. }
    90. break;
    91. default:
    92. // this->setDirectory(_appDir);
    93. break;
    94. }
    95. this->setLabelText(QFileDialog::Reject,tr("myCancel"));
    96. }

    FileQt.h的FileQt类是一个单体类,可以全局调用,实现txt、csv、ini、xls等文件读取、写入操作,支持文件目录、文件名等查询、读取、删除等操作,可以依据读写文件信息的API扩展新的功能或调整实现新文件类型的支持。

    1. #ifndef FILEQT_H
    2. #define FILEQT_H
    3. #include
    4. #include
    5. #include
    6. class FileQt
    7. {
    8. public:
    9. static FileQt* getInstance();
    10. static void Destroy();
    11. ~FileQt();
    12. bool writeListInfo(QVector list,const QString path,bool appendf=true);
    13. bool readListInfo(QVector > &list,const QString path,QString _div);
    14. bool readListInfo(QVector > &list,const QString path);
    15. bool readListInfo_dot(QVector > &list,const QString path);
    16. bool readListInfo(QVector &list,const QString path);
    17. void getAllFileName_dot(const QString directory, const QString extName, QStringList& fileNames);
    18. void getAllFileName(const QString& directory, const QString& extName, QStringList& fileNames);
    19. void getSubDir(const QString& directory, QStringList& subdirs);
    20. bool readToVectorXML(QString _file, QStringList elements, QVector &_lists);
    21. bool readToVectorXML(QString _file, QStringList elements, QVector > &_lists,QString _div=",");
    22. #ifdef WIN32
    23. bool readToVectorXLS(QString _file, QVector > &_lists, int sheet = 1);
    24. #endif
    25. private:
    26. bool readToVector(QString _file, QVector > &_lists,QString _div="\\s+");
    27. bool readToVector(QString _file, QVector &_lists);
    28. private:
    29. FileQt();
    30. FileQt(const FileQt& ) {} // copy constructor
    31. FileQt& operator=(const FileQt& ) { return *this; } // assignment operator
    32. private:
    33. static FileQt* instance;
    34. };
    35. #endif //FILEQT_H

    FileQt.cpp

    1. #include "FileQt.h"
    2. #include
    3. #include
    4. #include
    5. #include
    6. #include
    7. #include
    8. #include
    9. #include
    10. #include
    11. #include
    12. #include
    13. #ifdef WIN32
    14. #include
    15. #endif
    16. FileQt* FileQt::instance = NULL;
    17. FileQt* FileQt::getInstance()
    18. {
    19. if(NULL == FileQt::instance)
    20. {
    21. FileQt::instance = new FileQt();
    22. }
    23. return FileQt::instance;
    24. }
    25. void FileQt::Destroy()
    26. {
    27. if(NULL!=FileQt::instance){
    28. delete FileQt::instance;
    29. FileQt::instance = NULL;
    30. }
    31. }
    32. FileQt::FileQt()
    33. {
    34. }
    35. FileQt::~FileQt()
    36. {
    37. }
    38. bool FileQt::readListInfo(QVector > &list,const QString path,QString _div)
    39. {
    40. return readToVector(path,list,_div);
    41. }
    42. bool FileQt::readListInfo(QVector > &list,const QString path)
    43. {
    44. return readToVector(path,list,"\\W+");
    45. }
    46. bool FileQt::readListInfo_dot(QVector > &list,const QString path)
    47. {
    48. return readToVector(path,list,",");
    49. }
    50. bool FileQt::readListInfo(QVector &list,const QString path)
    51. {
    52. return readToVector(path,list);
    53. }
    54. bool FileQt::readToVector(QString _file,QVector > &_lists, QString _div)
    55. {
    56. #ifdef WIN32
    57. if (_file.contains(".xls", Qt::CaseInsensitive))
    58. {
    59. return readToVectorXLS(_file,_lists);
    60. }
    61. #endif
    62. QFile file(_file);
    63. if (!file.open(QFile::ReadOnly)) {
    64. qDebug() << "conn't open file " << _file << "!\n";
    65. return false;
    66. }else{
    67. QTextStream stream( &file );
    68. QString line;
    69. while ( !stream.atEnd() ) {
    70. line = stream.readLine();
    71. QStringList _strL = line.split(QRegExp(_div));
    72. // QStringList _strL = line.split(QRegExp(_div),QString::SkipEmptyParts);
    73. QVector _onev;
    74. for (int i = 0; i < _strL.size(); i++)
    75. {
    76. _onev.push_back(_strL[i]);
    77. }
    78. _lists.push_back(_onev);
    79. }
    80. file.close();
    81. if (_lists.empty())
    82. {
    83. return false;
    84. }else{
    85. return true;
    86. }
    87. }
    88. }
    89. bool FileQt::readToVector(QString _file, QVector &_lists)
    90. {
    91. QFile file(_file);
    92. if (!file.open(QFile::ReadOnly))
    93. {
    94. qDebug() << "conn't open file " << _file << "!\n";
    95. return false;
    96. }else{
    97. QTextStream stream( &file );
    98. stream.setCodec("UTF-8"); //中文编码
    99. QString line;
    100. while ( !stream.atEnd() ) {
    101. line = stream.readLine();
    102. _lists.push_back(line);
    103. }
    104. file.close();
    105. if (_lists.empty())
    106. {
    107. return false;
    108. }else{
    109. return true;
    110. }
    111. }
    112. }
    113. void FileQt::getAllFileName_dot(const QString directory, const QString extName, QStringList& fileNames)
    114. {
    115. QDir _dir(directory);
    116. QStringList filters;
    117. filters << ("*."+extName);
    118. _dir.setNameFilters(filters);
    119. _dir.setFilter(QDir::Files | QDir::NoDotAndDotDot | QDir::NoSymLinks);
    120. _dir.setSorting(QDir::Name);
    121. fileNames = _dir.entryList();
    122. qDebug() << fileNames << "\n";
    123. }
    124. void FileQt::getAllFileName(const QString& directory, const QString& extName, QStringList& fileNames)
    125. {
    126. QDir _dir(directory);
    127. QStringList filters;
    128. filters << ("*."+extName);
    129. _dir.setNameFilters(filters);
    130. _dir.setFilter(QDir::Files | QDir::NoDotAndDotDot | QDir::NoSymLinks);
    131. _dir.setSorting(QDir::Name);
    132. QStringList _files = _dir.entryList();
    133. for (int i = 0; i < _files.size(); i++)
    134. {
    135. fileNames << _files[i].left(_files[i].lastIndexOf("."));
    136. }
    137. qDebug() << fileNames << "\n";
    138. }
    139. void FileQt::getSubDir(const QString& directory, QStringList& subdirs)
    140. {
    141. QDir _dir(directory);
    142. _dir.setFilter(QDir::Dirs | QDir::NoDotAndDotDot | QDir::NoSymLinks);
    143. _dir.setSorting(QDir::Name);
    144. subdirs = _dir.entryList();
    145. qDebug() << subdirs << "\n";
    146. }
    147. bool FileQt::readToVectorXML(QString _file, QStringList elements, QVector &_lists)
    148. {
    149. QFile inputFile(_file);
    150. if(!inputFile.open(QFile::ReadOnly))
    151. {
    152. qDebug() << "cann't create file: "<< _file <<"\n";
    153. return false;
    154. }
    155. QByteArray data = inputFile.readAll();
    156. inputFile.close();
    157. QTextCodec *codec = QTextCodec::codecForHtml(data);
    158. QString str = codec->toUnicode(data);
    159. QXmlStreamReader reader(str);
    160. //reader.readNext();
    161. bool readF = false;
    162. while (!reader.atEnd()&&!reader.hasError())
    163. {
    164. reader.readNext();
    165. if (reader.error())
    166. {
    167. qDebug()<errorString()<<": "<name().toString()<<"\n";
    168. return false;
    169. } else{
    170. if (QXmlStreamReader::StartElement==reader.tokenType()
    171. && elements.contains(reader.name().toString()))
    172. {
    173. readF = true;
    174. continue;
    175. }
    176. if (QXmlStreamReader::EndElement==reader.tokenType()
    177. && elements.contains(reader.qualifiedName().toString()))
    178. {
    179. readF = false;
    180. continue;
    181. }
    182. if(readF){
    183. _lists.push_back(reader.text().toString());
    184. }
    185. }
    186. }
    187. return true;
    188. }
    189. bool FileQt::readToVectorXML(QString _file, QStringList elements, QVector > &_lists,QString _div)
    190. {
    191. QVector _list;
    192. if(readToVectorXML(_file,elements,_list)){
    193. for (int i = 0; i < _list.size(); i++)
    194. {
    195. QStringList _linelist = _list[i].split(QRegExp(_div));
    196. QVector _linevect;
    197. for (int j = 0; j < _linelist.size(); j++)
    198. {
    199. _linevect << _linelist[j];
    200. }
    201. _lists.push_back(_linevect);
    202. }
    203. return true;
    204. }
    205. return false;
    206. }
    207. #ifdef WIN32
    208. bool FileQt::readToVectorXLS(QString _file, QVector > &_lists, int sheet)
    209. {
    210. if(sheet<=0)
    211. {
    212. return false;
    213. }
    214. QAxObject *excel = NULL;
    215. QAxObject *workbooks = NULL;
    216. QAxObject *workbook = NULL;
    217. excel = new QAxObject("Excel.Application");//连接Excel控件
    218. if (!excel) {
    219. qDebug()<< QObject::tr("error info: ") << QObject::tr("EXCEL object loss") <<"\n";
    220. return false;
    221. }
    222. excel->dynamicCall("SetVisible(bool)", false);//不显示窗体
    223. excel->setProperty("DisplayAlerts", false);//不显示任何警告信息。
    224. workbooks = excel->querySubObject("WorkBooks");//获取工作簿集合
    225. workbook = workbooks->querySubObject("Open(QString, QVariant)", _file); //打开工作簿
    226. qDebug() << "workbooks size = " << workbook->querySubObject("WorkSheets")->property("Count").toInt() << "\n";
    227. if(sheet>workbook->querySubObject("WorkSheets")->property("Count").toInt()){
    228. delete workbook;
    229. workbook = NULL;
    230. delete workbooks;
    231. workbooks = NULL;
    232. delete excel;
    233. excel = NULL;
    234. return false;
    235. }
    236. QAxObject * worksheet = workbook->querySubObject("WorkSheets(int)", sheet);//打开第一个sheet
    237. QAxObject * usedrange = worksheet->querySubObject("UsedRange");//获取该sheet的使用范围对象
    238. int intRowStart = usedrange->property("Row").toInt();
    239. int intColStart = usedrange->property("Column").toInt();
    240. QAxObject * rows = usedrange->querySubObject("Rows");
    241. int intRows = rows->property("Count").toInt();
    242. QAxObject * columns = usedrange->querySubObject("Columns");
    243. int intCols = columns->property("Count").toInt();
    244. for (int i = intRowStart; i < intRowStart + intRows; i++)//row
    245. {
    246. QVector _onev;
    247. for (int j = intColStart; j < intColStart + intCols; j++)//column
    248. {
    249. // QAxObject * range = worksheet->querySubObject("Cells(QVariant,QVariant)", i, j ); //获取单元格
    250. // // qDebug() << i << j << range->property("Value");
    251. // _onev.push_back(range->property("Value").toString());
    252. _onev.push_back(
    253. worksheet->querySubObject("Cells(QVariant,QVariant)", i, j )->property("Value").toString());
    254. }
    255. _lists.push_back(_onev);
    256. }
    257. workbook->dynamicCall("Close()");//关闭工作簿
    258. excel->dynamicCall("Quit()");//关闭excel
    259. delete columns;
    260. columns = NULL;
    261. delete rows;
    262. rows = NULL;
    263. delete usedrange;
    264. usedrange = NULL;
    265. delete worksheet;
    266. worksheet = NULL;
    267. delete workbook;
    268. workbook = NULL;
    269. delete workbooks;
    270. workbooks = NULL;
    271. delete excel;
    272. excel = NULL;
    273. return true;
    274. }
    275. #endif
    276. bool FileQt::writeListInfo(QVector list,const QString path,bool appendf)
    277. {
    278. QFile f(path);
    279. if(!f.open(QFile::WriteOnly | QFile::Text | (appendf?QFile::Append:QFile::Truncate)))
    280. return false;
    281. QTextStream out(&f);
    282. out.setCodec("UTF-8"); //中文编码
    283. for (int i = 0; i < list.size(); i++)
    284. {
    285. out << QString(list[i]);
    286. }
    287. f.close();
    288. return true;
    289. }

    inOrOutConf.h实现简要的界面窗口,

    提供sqlite数据库文件路径及csv文件目录编辑以及两个转换按钮。

    1. #ifndef INOROUT_CONF_H
    2. #define INOROUT_CONF_H
    3. #include
    4. class QLineEdit;
    5. class QPushButton;
    6. class QLabel;
    7. class InOrOutConf : public QWidget
    8. {
    9. Q_OBJECT
    10. public:
    11. InOrOutConf(QWidget * parent = 0,Qt::WindowFlags f = 0);
    12. ~InOrOutConf();
    13. private slots:
    14. void setDBPath();
    15. void setCsvPath();
    16. void scvToDB();
    17. void DBToCsv();
    18. private:
    19. QString divPath;
    20. QLineEdit *pathEdit; //db路径编辑框
    21. QPushButton *pathset; //db路径打开
    22. QLineEdit *dirEdit; //文件目录编辑框
    23. QPushButton *dirset; //文件目录打开
    24. QPushButton *inButton; //csv到db
    25. QPushButton *outButton; //db到csv
    26. QPushButton *close; //
    27. QLabel *warLabel;
    28. };
    29. #endif //INOROUT_CONF_H

    inOrOutConf.cpp,注意inYc、outYc等API主要实现关于表格名、列表名特定处理,暂没做抽象提取及可配置实现。

    1. #include "inOrOutConf.h"
    2. #include
    3. #include
    4. #include
    5. #include
    6. #include
    7. #include
    8. #include
    9. #include
    10. #include
    11. #include
    12. #include
    13. #include
    14. #ifdef WIN32
    15. #include
    16. Q_IMPORT_PLUGIN(QSQLiteDriverPlugin)
    17. #endif
    18. #include
    19. #include
    20. #include
    21. // #include "sqlite/sqlite3.h"
    22. // #include "sqlite/CSQLite.h"
    23. #include "file/myfiledialog.h"
    24. #include "file/strcode.hpp"
    25. // //101YC配置表
    26. // typedef struct _s101yc{
    27. // int INDEXID;
    28. // int DEVID;
    29. // char NAME[256];
    30. // unsigned int LOCALADDR;
    31. // double COEF;
    32. // double THV;
    33. // char NAMETOMST[256];
    34. // unsigned int ZEROVAL;
    35. // unsigned int SAMPADDR;
    36. // unsigned int SAMPDEVID;
    37. // char EXPLAIN[256];
    38. // }s101yc;
    39. // //101YX配置表
    40. // typedef struct _s101yx{
    41. // int INDEXID;
    42. // int DEVID;
    43. // char NAME[256];
    44. // unsigned int LOCALADDR;
    45. // unsigned int NOT;
    46. // unsigned int SAMPDEVID;
    47. // unsigned int SAMPADDR;
    48. // char NAMETOMST[256];
    49. // }s101yx;
    50. // //101YK配置表
    51. // typedef struct _s101yk{
    52. // int INDEXID;
    53. // unsigned int LOCALADDR;
    54. // int DEVID;
    55. // char NAME[256];
    56. // unsigned int SAMPDEVID;
    57. // unsigned int SAMPADDR;
    58. // char NAMETOMST[256];
    59. // }s101yk;
    60. // //YC
    61. // int GetS101yc(const char * dbfile, const char* condition, s101yc * ycs, int size)
    62. // {
    63. // CSQLiteDB db;
    64. // if( !db.open(dbfile) ){
    65. // printf("open db: error!", dbfile);
    66. // return -1;
    67. // }
    68. // char sql[1024] ={0};
    69. // if( strlen(condition) > 0 )
    70. // sprintf(sql,"select * from s101yc where %s", condition);
    71. // else
    72. // sprintf(sql,"select * from s101yc");
    73. // int icount = 0;
    74. // CSQLiteQuery query;
    75. // try{
    76. // query = db.execQuery(sql);
    77. // while( !query.eof() && icount
    78. // ycs[icount].INDEXID = query.getIntField("INDEXID");
    79. // ycs[icount].DEVID = query.getIntField("DEVID");
    80. // strcpy( ycs[icount].NAME,query.getStringField("NAME"));
    81. // ycs[icount].LOCALADDR = query.getIntField("LOCALADDR");
    82. // ycs[icount].COEF = query.getFloatField("COEF");
    83. // ycs[icount].THV = query.getFloatField("THV");
    84. // strcpy( ycs[icount].NAMETOMST,query.getStringField("NAMETOMST"));
    85. // ycs[icount].ZEROVAL = query.getIntField("ZEROVAL");
    86. // ycs[icount].SAMPADDR = query.getIntField("SAMPADDR");
    87. // ycs[icount].SAMPDEVID = query.getIntField("SAMPDEVID");
    88. // strcpy( ycs[icount].EXPLAIN,query.getStringField("EXPLAIN"));
    89. // icount++;
    90. // query.nextRow();
    91. // }
    92. // }catch (CSQLiteException& e) {
    93. // printf("db query error %d\n",e.errorCode());
    94. // return -1;
    95. // }
    96. // return icount;
    97. // };
    98. InOrOutConf::InOrOutConf(QWidget * parent,Qt::WindowFlags f)
    99. : QWidget(parent,f)
    100. {
    101. pathEdit = new QLineEdit(this);
    102. pathEdit->setMinimumWidth(200);
    103. pathset = new QPushButton(tr("dbOpen"),this);
    104. pathset->setMaximumWidth(72);
    105. connect(pathset,SIGNAL(clicked()),this,SLOT(setDBPath()));
    106. //layout
    107. QFormLayout *formLayout_00 = new QFormLayout;
    108. formLayout_00->setContentsMargins(0,0,0,0);
    109. formLayout_00->addRow(tr("dbPath:"), pathEdit);
    110. QHBoxLayout *m_QHBoxLayout_00 = new QHBoxLayout;
    111. m_QHBoxLayout_00->setContentsMargins(0,0,0,0);
    112. m_QHBoxLayout_00->addLayout(formLayout_00);
    113. m_QHBoxLayout_00->addWidget(pathset);
    114. dirEdit = new QLineEdit(this);
    115. dirEdit->setMinimumWidth(200);
    116. dirset = new QPushButton(tr("scvDirCheck"),this);
    117. dirset->setMaximumWidth(72);
    118. connect(dirset,SIGNAL(clicked()),this,SLOT(setCsvPath()));
    119. //layout
    120. QFormLayout *formLayout_01 = new QFormLayout;
    121. formLayout_01->setContentsMargins(0,0,0,0);
    122. formLayout_01->addRow(tr("scvDir:"), dirEdit);
    123. QHBoxLayout *m_QHBoxLayout_01 = new QHBoxLayout;
    124. m_QHBoxLayout_01->setContentsMargins(0,0,0,0);
    125. m_QHBoxLayout_01->addLayout(formLayout_01);
    126. m_QHBoxLayout_01->addWidget(dirset);
    127. QVBoxLayout *m_QVBoxLayout = new QVBoxLayout;
    128. m_QVBoxLayout->addLayout(m_QHBoxLayout_00);
    129. m_QVBoxLayout->addLayout(m_QHBoxLayout_01);
    130. warLabel = new QLabel(this);
    131. inButton = new QPushButton(tr("scvToDB"),this);
    132. inButton->setMaximumWidth(72);
    133. connect(inButton,SIGNAL(clicked()),this,SLOT(scvToDB()));
    134. outButton = new QPushButton(tr("DBToCsv"),this);
    135. outButton->setMaximumWidth(72);
    136. connect(outButton,SIGNAL(clicked()),this,SLOT(DBToCsv()));
    137. close = new QPushButton(tr("Close"),this);
    138. close->setMaximumWidth(72);
    139. connect(close,SIGNAL(clicked()),this,SLOT(close()));
    140. QGridLayout *_QGridLayout = new QGridLayout(this);
    141. _QGridLayout->addLayout(m_QVBoxLayout,0,0,2,10);
    142. _QGridLayout->addWidget(warLabel,2,0,1,10);
    143. _QGridLayout->addWidget(inButton,3,7,1,1);
    144. _QGridLayout->addWidget(outButton,3,8,1,1);
    145. _QGridLayout->addWidget(close,3,9,1,1);
    146. #ifdef WIN32
    147. divPath = "\\";
    148. #else
    149. divPath = "/";
    150. #endif
    151. };
    152. InOrOutConf::~InOrOutConf()
    153. {
    154. };
    155. void InOrOutConf::setDBPath()
    156. {
    157. QString dbPath = QCoreApplication::applicationDirPath()+divPath+"exxconf.db";
    158. MyFileDialog *fileDialog = new MyFileDialog(this,4,tr("open DB file"),dbPath);
    159. if(fileDialog->exec() == QDialog::Accepted) {
    160. dbPath = fileDialog->selectedFiles()[0];
    161. }
    162. qDebug() << "dbPath = "<"\n";
    163. this->pathEdit->setText(dbPath);
    164. };
    165. void InOrOutConf::setCsvPath()
    166. {
    167. QString csvDir = QCoreApplication::applicationDirPath();
    168. MyFileDialog *fileDialog = new MyFileDialog(this,3,tr("open CSV dir"),csvDir);
    169. if(fileDialog->exec() == QDialog::Accepted) {
    170. csvDir = fileDialog->selectedFiles()[0];
    171. }
    172. qDebug() << "csvDir = "<"\n";
    173. this->dirEdit->setText(csvDir);
    174. };
    175. bool executeSQL(QSqlDatabase db,QString _sql)
    176. {
    177. QSqlQuery query(db);
    178. return query.exec(_sql);
    179. };
    180. bool checkTable(QSqlDatabase db, QString _table)
    181. {
    182. QString _sql = QString("select count(*) from sqlite_master where type='table' and name='%1'").arg(_table);
    183. QSqlQuery query(db);
    184. query.exec(_sql);
    185. bool _existTable = true;
    186. if (query.next())
    187. {
    188. int _countTable = query.value(0).toInt();
    189. if (1!=_countTable)
    190. {
    191. _existTable = false;
    192. }
    193. }else{
    194. _existTable = false;
    195. }
    196. return _existTable;
    197. };
    198. bool opendb(QSqlDatabase &db, QString _dbn,QString _dbLink)
    199. {
    200. QString dbv = "QSQLITE";
    201. // QString _dbLink = "db_sqlite_record";
    202. if (QSqlDatabase::contains(_dbLink))
    203. {
    204. db = QSqlDatabase::database(_dbLink);
    205. }else{
    206. db = QSqlDatabase::addDatabase(dbv,_dbLink);
    207. }
    208. // checkDBLink(_dbLink);
    209. // db = QSqlDatabase::addDatabase(dbv,_dbLink);
    210. db.setDatabaseName(_dbn);
    211. if (db.open())
    212. {
    213. return true;
    214. }else{
    215. qDebug() << "open db failed!"<< "---"<< db.lastError().text()<<" \n";
    216. return false;
    217. }
    218. };
    219. bool checkdb_etconf(QSqlDatabase &db, QString _dbn)
    220. {
    221. if (!opendb(db,_dbn,"db_sqlite_etconf"))
    222. {
    223. return false;
    224. }else{
    225. if(!executeSQL(db,"PRAGMA synchronous = OFF"))
    226. {
    227. qDebug() << db.lastError() << "\n";
    228. }
    229. }
    230. if(!checkTable(db,"s101yc"))
    231. {
    232. return false;
    233. }
    234. if(!checkTable(db,"s101yx"))
    235. {
    236. return false;
    237. }
    238. if(!checkTable(db,"s101yk"))
    239. {
    240. return false;
    241. }
    242. if(!checkTable(db,"s101yt"))
    243. {
    244. return false;
    245. }
    246. return true;
    247. };
    248. bool readToVector(QString _file,QVector > &_lists, QString _div)
    249. {
    250. QFile file(_file);
    251. if (!file.open(QFile::ReadOnly)) {
    252. qDebug() << "conn't open file " << _file << "!\n";
    253. return false;
    254. }else{
    255. QTextStream stream( &file );
    256. QString line;
    257. while ( !stream.atEnd() ) {
    258. line = stream.readLine();
    259. QStringList _strL = line.split(QRegExp(_div));
    260. // QStringList _strL = line.split(QRegExp(_div),QString::SkipEmptyParts);
    261. QVector _onev;
    262. for (int i = 0; i < _strL.size(); i++)
    263. {
    264. _onev.push_back(_strL[i]);
    265. }
    266. _lists.push_back(_onev);
    267. }
    268. file.close();
    269. if (_lists.empty())
    270. {
    271. return false;
    272. }else{
    273. return true;
    274. }
    275. }
    276. }
    277. void inYc(QSqlDatabase &db,QString _path)
    278. {
    279. QVector > _lists;
    280. readToVector(_path,_lists,",");
    281. QSqlQuery query(db);
    282. query.exec("DELETE FROM s101yc");
    283. QVariantList indexids;
    284. QVariantList devids;
    285. QVariantList names;
    286. QVariantList localaddrs;
    287. QVariantList coefs;
    288. QVariantList thvs;
    289. QVariantList nametomsts;
    290. QVariantList zerovals;
    291. QVariantList sampaddrs;
    292. QVariantList sampdevids;
    293. QVariantList explains;
    294. int _count = 0;
    295. QString _sql = "INSERT INTO s101yc (INDEXID,DEVID,NAME,LOCALADDR,COEF,THV,NAMETOMST,ZEROVAL,SAMPADDR,SAMPDEVID,EXPLAIN) "
    296. "VALUES (?,?,?,?,?,?,?,?,?,?,?)";
    297. for (int i = 0; i < _lists.size(); i++)
    298. {
    299. if (11!=_lists[i].size())
    300. {
    301. continue;
    302. }
    303. indexids << _lists[i][0].toInt();
    304. devids << _lists[i][1].toInt();
    305. names << _lists[i][2];
    306. // names << QString("%1").arg(_lists[i][2].toAscii().data());
    307. localaddrs << _lists[i][3].toInt();
    308. coefs << _lists[i][4].toDouble();
    309. thvs << _lists[i][5].toDouble();
    310. nametomsts << _lists[i][6];
    311. // nametomsts << QString("%1").arg(_lists[i][6].toAscii().data());
    312. zerovals << _lists[i][7].toInt();
    313. sampaddrs << _lists[i][8].toInt();
    314. sampdevids << _lists[i][9].toInt();
    315. explains << _lists[i][10];
    316. // explains << QString("%1").arg(_lists[i][10].toAscii().data());
    317. _count+=1;
    318. if (_count>=200||(i==(_lists.size()-1)))
    319. {
    320. try{
    321. query.prepare(_sql);
    322. query.addBindValue(indexids);
    323. query.addBindValue(devids);
    324. query.addBindValue(names);
    325. query.addBindValue(localaddrs);
    326. query.addBindValue(coefs);
    327. query.addBindValue(thvs);
    328. query.addBindValue(nametomsts);
    329. query.addBindValue(zerovals);
    330. query.addBindValue(sampaddrs);
    331. query.addBindValue(sampdevids);
    332. query.addBindValue(explains);
    333. if (!query.execBatch())
    334. {
    335. qDebug() << query.lastError();
    336. }
    337. }catch(...){
    338. qDebug() << query.lastError();
    339. }
    340. indexids.clear();
    341. devids.clear();
    342. names.clear();
    343. localaddrs.clear();
    344. coefs.clear();
    345. thvs.clear();
    346. nametomsts.clear();
    347. zerovals.clear();
    348. sampaddrs.clear();
    349. sampdevids.clear();
    350. explains.clear();
    351. _count = 0;
    352. }
    353. }
    354. };
    355. void inYx(QSqlDatabase &db,QString _path)
    356. {
    357. QVector > _lists;
    358. readToVector(_path,_lists,",");
    359. QSqlQuery query(db);
    360. query.exec("DELETE FROM s101yx");
    361. QVariantList indexids;
    362. QVariantList devids;
    363. QVariantList names;
    364. QVariantList localaddrs;
    365. QVariantList nots;
    366. QVariantList sampdevids;
    367. QVariantList sampaddrs;
    368. QVariantList nametomsts;
    369. int _count = 0;
    370. QString _sql = "INSERT INTO s101yx (INDEXID,DEVID,NAME,LOCALADDR,\"NOT\",SAMPDEVID,SAMPADDR,NAMETOMST) "
    371. "VALUES (?,?,?,?,?,?,?,?)";
    372. for (int i = 0; i < _lists.size(); i++)
    373. {
    374. if (8!=_lists[i].size())
    375. {
    376. continue;
    377. }
    378. indexids << _lists[i][0].toInt();
    379. devids << _lists[i][1].toInt();
    380. names << _lists[i][2];
    381. // names << QString("%1").arg(_lists[i][2].toAscii().data());
    382. localaddrs << _lists[i][3].toInt();
    383. nots << _lists[i][4].toInt();
    384. sampdevids << _lists[i][5].toInt();
    385. sampaddrs << _lists[i][6].toInt();
    386. nametomsts << _lists[i][7];
    387. // nametomsts << QString("%1").arg(_lists[i][7].toAscii().data());
    388. _count+=1;
    389. if (_count>=200||(i==(_lists.size()-1)))
    390. {
    391. try{
    392. query.prepare(_sql);
    393. query.addBindValue(indexids);
    394. query.addBindValue(devids);
    395. query.addBindValue(names);
    396. query.addBindValue(localaddrs);
    397. query.addBindValue(nots);
    398. query.addBindValue(sampdevids);
    399. query.addBindValue(sampaddrs);
    400. query.addBindValue(nametomsts);
    401. if (!query.execBatch())
    402. {
    403. qDebug() << query.lastError();
    404. }
    405. }catch(...){
    406. qDebug() << query.lastError();
    407. }
    408. indexids.clear();
    409. devids.clear();
    410. names.clear();
    411. localaddrs.clear();
    412. nots.clear();
    413. sampdevids.clear();
    414. sampaddrs.clear();
    415. nametomsts.clear();
    416. _count = 0;
    417. }
    418. }
    419. };
    420. void inYk(QSqlDatabase &db,QString _path)
    421. {
    422. QVector > _lists;
    423. readToVector(_path,_lists,",");
    424. QSqlQuery query(db);
    425. query.exec("DELETE FROM s101yk");
    426. QVariantList indexids;
    427. QVariantList localaddrs;
    428. QVariantList devids;
    429. QVariantList names;
    430. QVariantList sampaddrs;
    431. QVariantList sampdevids;
    432. QVariantList nametomsts;
    433. int _count = 0;
    434. QString _sql = "INSERT INTO s101yk (INDEXID,LOCALADDR,DEVID,NAME,SAMPADDR,SAMPDEVID,NAMETOMST) "
    435. "VALUES (?,?,?,?,?,?,?)";
    436. for (int i = 0; i < _lists.size(); i++)
    437. {
    438. if (7!=_lists[i].size())
    439. {
    440. continue;
    441. }
    442. indexids << _lists[i][0].toInt();
    443. localaddrs << _lists[i][1].toInt();
    444. devids << _lists[i][2].toInt();
    445. names << _lists[i][3];
    446. // names << QString("%1").arg(_lists[i][3].toAscii().data());
    447. sampaddrs << _lists[i][4].toInt();
    448. sampdevids << _lists[i][5].toInt();
    449. nametomsts << _lists[i][6];
    450. // nametomsts << QString("%1").arg(_lists[i][6].toAscii().data());
    451. _count+=1;
    452. if (_count>=200||(i==(_lists.size()-1)))
    453. {
    454. try{
    455. query.prepare(_sql);
    456. query.addBindValue(indexids);
    457. query.addBindValue(localaddrs);
    458. query.addBindValue(devids);
    459. query.addBindValue(names);
    460. query.addBindValue(sampaddrs);
    461. query.addBindValue(sampdevids);
    462. query.addBindValue(nametomsts);
    463. if (!query.execBatch())
    464. {
    465. qDebug() << query.lastError();
    466. }
    467. }catch(...){
    468. qDebug() << query.lastError();
    469. }
    470. indexids.clear();
    471. localaddrs.clear();
    472. devids.clear();
    473. names.clear();
    474. sampaddrs.clear();
    475. sampdevids.clear();
    476. nametomsts.clear();
    477. _count = 0;
    478. }
    479. }
    480. };
    481. void inYt(QSqlDatabase &db,QString _path)
    482. {
    483. QVector > _lists;
    484. readToVector(_path,_lists,",");
    485. QSqlQuery query(db);
    486. query.exec("DELETE FROM s101yt");
    487. QVariantList indexids;
    488. QVariantList localaddrs;
    489. QVariantList devids;
    490. QVariantList names;
    491. QVariantList sampaddrs;
    492. QVariantList sampdevids;
    493. QVariantList nametomsts;
    494. int _count = 0;
    495. QString _sql = "INSERT INTO s101yt (INDEXID,LOCALADDR,DEVID,NAME,SAMPADDR,SAMPDEVID,NAMETOMST) "
    496. "VALUES (?,?,?,?,?,?,?)";
    497. for (int i = 0; i < _lists.size(); i++)
    498. {
    499. if (7!=_lists[i].size())
    500. {
    501. continue;
    502. }
    503. indexids << _lists[i][0].toInt();
    504. localaddrs << _lists[i][1].toInt();
    505. devids << _lists[i][2].toInt();
    506. names << _lists[i][3];
    507. // names << QString("%1").arg(_lists[i][3].toAscii().data());
    508. sampaddrs << _lists[i][4].toInt();
    509. sampdevids << _lists[i][5].toInt();
    510. nametomsts << _lists[i][6];
    511. // nametomsts << QString("%1").arg(_lists[i][6].toAscii().data());
    512. _count+=1;
    513. if (_count>=200||(i==(_lists.size()-1)))
    514. {
    515. try{
    516. query.prepare(_sql);
    517. query.addBindValue(indexids);
    518. query.addBindValue(localaddrs);
    519. query.addBindValue(devids);
    520. query.addBindValue(names);
    521. query.addBindValue(sampaddrs);
    522. query.addBindValue(sampdevids);
    523. query.addBindValue(nametomsts);
    524. if (!query.execBatch())
    525. {
    526. qDebug() << query.lastError();
    527. }
    528. }catch(...){
    529. qDebug() << query.lastError();
    530. }
    531. indexids.clear();
    532. localaddrs.clear();
    533. devids.clear();
    534. names.clear();
    535. sampaddrs.clear();
    536. sampdevids.clear();
    537. nametomsts.clear();
    538. _count = 0;
    539. }
    540. }
    541. };
    542. void InOrOutConf::scvToDB()
    543. {
    544. QString _dbn = this->pathEdit->text();
    545. QFile _file(_dbn);
    546. if (!_file.exists())
    547. {
    548. warLabel->setText("db isn't exist!");
    549. return;
    550. }
    551. QSqlDatabase db;
    552. if(!checkdb_etconf(db,_dbn))
    553. {
    554. warLabel->setText("db isn't table we need!");
    555. return;
    556. }
    557. warLabel->setText("csv to db runing!");
    558. inYc(db,this->dirEdit->text()+divPath+"s101yc.csv");
    559. inYx(db,this->dirEdit->text()+divPath+"s101yx.csv");
    560. inYk(db,this->dirEdit->text()+divPath+"s101yk.csv");
    561. inYt(db,this->dirEdit->text()+divPath+"s101yt.csv");
    562. warLabel->setText("csv to db finish!");
    563. db.close();
    564. };
    565. bool writeListInfo(QVector list,const QString path,bool appendf)
    566. {
    567. QFile f(path);
    568. if(!f.open(QFile::WriteOnly | QFile::Text | (appendf?QFile::Append:QFile::Truncate)))
    569. return false;
    570. QTextStream out(&f);
    571. // out.setCodec("UTF-8"); //中文编码
    572. for (int i = 0; i < list.size(); i++)
    573. {
    574. out << QString(list[i]);
    575. }
    576. f.close();
    577. return true;
    578. };
    579. void outYc(QSqlDatabase &db,QString _path)
    580. {
    581. QSqlQuery query(db);
    582. QString _sql = "select INDEXID,DEVID,NAME,LOCALADDR,COEF,THV,NAMETOMST,ZEROVAL,SAMPADDR,SAMPDEVID,EXPLAIN from s101yc";
    583. query.prepare(_sql);
    584. query.exec();
    585. QVector list;
    586. QString _sb = QObject::tr("shebei");
    587. QString _cj = QObject::tr("caiji");
    588. while (query.next()) {
    589. QString _line = "";
    590. for (int i = 0; i < 11; i++)
    591. {
    592. _line+=query.value(i).toString();
    593. if (i!=10)
    594. {
    595. _line+=",";
    596. }
    597. }
    598. _line+="\n";
    599. // _line = QString("%1").arg(ASCII2UTF_8(_line.toStdString()).c_str());
    600. // _line.replace(QString("??"), _sb);
    601. // _line.replace(QString("?"), _cj);
    602. list.push_back(_line);
    603. // char *buf= new char[512];
    604. // buf = G2U(_line.toStdString().c_str());
    605. // list.push_back( QString("%1").arg(buf));
    606. // qDebug()<<"_line="<<_line<<"\n";
    607. // qDebug()<<"_line_utf="<
    608. if (list.size()>1000)
    609. {
    610. writeListInfo(list,_path,true);
    611. list.clear();
    612. }
    613. }
    614. writeListInfo(list,_path,true);
    615. list.clear();
    616. };
    617. void outYx(QSqlDatabase &db,QString _path)
    618. {
    619. QSqlQuery query(db);
    620. QString _sql = "select INDEXID,DEVID,NAME,LOCALADDR,\"NOT\",SAMPDEVID,SAMPADDR,NAMETOMST from s101yx";
    621. query.prepare(_sql);
    622. query.exec();
    623. QVector list;
    624. while (query.next()) {
    625. QString _line = "";
    626. for (int i = 0; i < 8; i++)
    627. {
    628. _line+=query.value(i).toString();
    629. if (i!=7)
    630. {
    631. _line+=",";
    632. }
    633. }
    634. _line+="\n";
    635. // _line = QString("%1").arg(ASCII2UTF_8(_line.toStdString()).c_str());
    636. // _line.replace(QString("??"), QObject::tr("shebei"));
    637. // _line.replace(QString("?"), QObject::tr("caiji"));
    638. list.push_back(_line);
    639. // char *buf= new char[512];
    640. // buf = G2U(_line.toStdString().c_str());
    641. // list.push_back( QString("%1").arg(buf));
    642. // qDebug()<<"_line="<<_line<<"\n";
    643. // qDebug()<<"_line_utf="<
    644. if (list.size()>1000)
    645. {
    646. writeListInfo(list,_path,true);
    647. list.clear();
    648. }
    649. }
    650. writeListInfo(list,_path,true);
    651. list.clear();
    652. };
    653. void outYk(QSqlDatabase &db,QString _path)
    654. {
    655. QSqlQuery query(db);
    656. QString _sql = "select INDEXID,LOCALADDR,DEVID,NAME,SAMPADDR,SAMPDEVID,NAMETOMST from s101yk";
    657. query.prepare(_sql);
    658. query.exec();
    659. QVector list;
    660. while (query.next()) {
    661. QString _line = "";
    662. for (int i = 0; i < 7; i++)
    663. {
    664. _line+=query.value(i).toString();
    665. if (i!=6)
    666. {
    667. _line+=",";
    668. }
    669. }
    670. _line+="\n";
    671. // _line = QString("%1").arg(ASCII2UTF_8(_line.toStdString()).c_str());
    672. // _line.replace(QString("??"), QObject::tr("shebei"));
    673. // _line.replace(QString("?"), QObject::tr("caiji"));
    674. list.push_back(_line);
    675. // char *buf= new char[512];
    676. // buf = G2U(_line.toStdString().c_str());
    677. // list.push_back( QString("%1").arg(buf));
    678. // qDebug()<<"_line="<<_line<<"\n";
    679. // qDebug()<<"_line_utf="<
    680. if (list.size()>1000)
    681. {
    682. writeListInfo(list,_path,true);
    683. list.clear();
    684. }
    685. }
    686. writeListInfo(list,_path,true);
    687. list.clear();
    688. };
    689. void outYt(QSqlDatabase &db,QString _path)
    690. {
    691. QSqlQuery query(db);
    692. QString _sql = "select INDEXID,LOCALADDR,DEVID,NAME,SAMPADDR,SAMPDEVID,NAMETOMST from s101yt";
    693. query.prepare(_sql);
    694. query.exec();
    695. QVector list;
    696. while (query.next()) {
    697. QString _line = "";
    698. for (int i = 0; i < 7; i++)
    699. {
    700. _line+=query.value(i).toString();
    701. if (i!=6)
    702. {
    703. _line+=",";
    704. }
    705. }
    706. _line+="\n";
    707. // _line = QString("%1").arg(ASCII2UTF_8(_line.toStdString()).c_str());
    708. // _line.replace(QString("??"), QObject::tr("shebei"));
    709. // _line.replace(QString("?"), QObject::tr("caiji"));
    710. list.push_back(_line);
    711. // char *buf= new char[512];
    712. // buf = G2U(_line.toStdString().c_str());
    713. // list.push_back( QString("%1").arg(buf));
    714. // qDebug()<<"_line="<<_line<<"\n";
    715. // qDebug()<<"_line_utf="<
    716. if (list.size()>1000)
    717. {
    718. writeListInfo(list,_path,true);
    719. list.clear();
    720. }
    721. }
    722. writeListInfo(list,_path,true);
    723. list.clear();
    724. };
    725. void InOrOutConf::DBToCsv()
    726. {
    727. QString _dbn = this->pathEdit->text();
    728. QFile _file(_dbn);
    729. if (!_file.exists())
    730. {
    731. warLabel->setText("db isn't exist!");
    732. return;
    733. }
    734. // s101yc * ycs = new s101yc[10];
    735. // int ret = GetS101yc(_dbn.toStdString().c_str(),"",ycs,10);
    736. // if(ret>0){
    737. // for (int i = 0; i < ret; i++)
    738. // {
    739. // qDebug() << QString("%1").arg(ycs[i].NAME)<<"\n";
    740. // qDebug() << QString("%1").arg(G2U(ycs[i].NAME))<<"\n";
    741. // qDebug() << QString("%1").arg(U2G(ycs[i].NAME))<<"\n";
    742. // qDebug() << QString("%1").arg(ASCII2UTF_8(std::string(ycs[i].NAME)).c_str())<<"\n";
    743. // qDebug() << QString("%1").arg(UTF_82ASCII(std::string(ycs[i].NAME)).c_str())<<"\n";
    744. // }
    745. // }
    746. QSqlDatabase db;
    747. if(!checkdb_etconf(db,_dbn))
    748. {
    749. warLabel->setText("db isn't table we need!");
    750. return;
    751. }
    752. warLabel->setText("db to csv runing!");
    753. outYc(db,this->dirEdit->text()+divPath+"s101yc.csv");
    754. outYx(db,this->dirEdit->text()+divPath+"s101yx.csv");
    755. outYk(db,this->dirEdit->text()+divPath+"s101yk.csv");
    756. outYt(db,this->dirEdit->text()+divPath+"s101yt.csv");
    757. warLabel->setText("db to csv finish!");
    758. db.close();
    759. };

    main.cpp

    1. #include
    2. #include
    3. #include
    4. #include "view/inOrOutConf.h"
    5. //主函数入口
    6. int main(int argc, char *argv[])
    7. {
    8. //app构造
    9. QApplication app(argc, argv);
    10. //languages translation, main event is translate Marco tr("")
    11. QTranslator translator;
    12. //装载翻译文件
    13. //lupdate *.pro导出源文代码
    14. translator.load(":/languages/dbInOrOut_cn.qm");
    15. //app.setFont(QFont("wenquanyi")); //set font stype lib
    16. app.installTranslator(&translator);
    17. // //设置本地语言
    18. // QTextCodec::setCodecForLocale(QTextCodec::codecForLocale());
    19. // QTextCodec::setCodecForCStrings(QTextCodec::codecForLocale());
    20. // QTextCodec::setCodecForTr(QTextCodec::codecForLocale());
    21. InOrOutConf w;
    22. w.show();
    23. return app.exec();
    24. }

    四、编译及测试

            qmake -o Makefile dbIntOrOut.pro && make debug | make release(win use nmake)

            运行效果如下:

     五、附件

            上面已近给出了全部源码,如果还是无法建立工程,以下是完整工程代码下载连接:

    qt实现的sqlites数据库文件与csv文件相互转换案例代码-C++文档类资源-CSDN下载

  • 相关阅读:
    智慧用电解决方案-最新全套文件
    Java开发琐碎语法(长期更新)
    Android驱动开发之如何编译和更换内核
    【会议资源】2022年第三届自动化科学与工程国际会议(JCASE 2022)
    java并发数据结构之CopyOnWriteArrayList
    前端之一阶段[HTML、CSS]问题记录
    python数据分析小案例:把招聘数据做可视化处理~
    潮流来袭!中国首届虚拟艺术巡展NFS将在广州YCC!天宜盛大开启!
    JS - WebAPI 基础
    Kotlin协程:挂起与恢复原理逆向刨析
  • 原文地址:https://blog.csdn.net/py8105/article/details/127133837