MFC listcontrol导出excel表格
// 导出Excel
CString CBackGroundDlg::ExportAsExcel(CString filename, CListCtrl &resultlist, CWnd * wnd)
{
CDatabase database;
CString sDriver = "MICROSOFT EXCEL DRIVER (*.XLS)"; // Excel安装驱动
CString sSql, sExcelFile;
//弹出对话框选择路径
CFileDialog fileDlg (FALSE, /*"Path",*/"xls", filename, OFN_FILEMUSTEXIST| OFN_HIDEREADONLY, "*.xls", wnd);
if(fileDlg.DoModal() == IDOK)
{
sExcelFile = fileDlg.GetPathName(); // 要建立的Excel文件
CFileFind finder;
BOOL bWorking = finder.FindFile(sExcelFile);//寻找文件
if (bWorking)//如果已经存在文件,则删除
{
CFile::Remove((LPCTSTR)sExcelFile);
}
}
else
return("");
TRY
{
// 创建进行存取的字符串
sSql.Format("DRIVER={%s};DSN='';FIRSTROWHASNAMES=1;READONLY=FALSE;CREATE_DB=\"%s\";DBQ=%s", sDriver, sExcelFile, sExcelFile);
// 创建数据库 (既Excel表格文件)
if(database.OpenEx(sSql, CDatabase::noOdbcDialog))
{
CHeaderCtrl* pHeader = resultlist.GetHeaderCtrl();
//获得行,列的个数
int nColCount = pHeader->GetItemCount();
int nLineCount = resultlist.GetItemCount();
int ColOrderArray[100];
CString ca[100];
resultlist.GetColumnOrderArray(ColOrderArray, nColCount);
//检索各列的信息,确定列标题的内容
for(int i =0 ; i< nColCount; i++)
{
LVCOLUMN lvc;
char text[100];
lvc.mask = LVCF_TEXT|LVCF_SUBITEM;
lvc.pszText = text;
lvc.cchTextMax = 100;
resultlist.GetColumn(ColOrderArray[i], &lvc);
ca[i] = lvc.pszText;
}
// 创建表结构
CString tempsql="(";
for(int i = 0 ; i < nColCount - 1; i++)
{
tempsql += ca[i];
tempsql += " TEXT,";
}
tempsql += ca[nColCount - 1];
tempsql += " TEXT)";
sSql = "CREATE TABLE Sheet1 ";
sSql += tempsql;
database.ExecuteSQL(sSql);
//插入数据
int item_count = resultlist.GetItemCount();
tempsql="(";
for(int i = 0 ; i < nColCount - 1; i++)
{
tempsql += ca[i];
tempsql += " ,";
}
tempsql += ca[nColCount - 1];
tempsql += ")";
for(int itemnum = 0; itemnum < item_count; itemnum++){
sSql = "";
sSql ="INSERT INTO Sheet1 ";
sSql += tempsql;
sSql += "VALUES ('";
for(int i =0 ; i < nColCount - 1; i++)
{
sSql += resultlist.GetItemText(itemnum, i);
sSql += "','";
}
sSql += resultlist.GetItemText(itemnum, nColCount - 1);
sSql += "')";
database.ExecuteSQL(sSql);
}
}
// 关闭数据库
database.Close();
AfxMessageBox("Excel文件写入成功!");
}
CATCH_ALL(e)
{
TRACE1("Excel驱动没有安装: %s", sDriver);
sExcelFile = "";
}
END_CATCH_ALL;
return sExcelFile;
}
//以下是调用该接口方法
CListCtrl *pList = (CListCtrl*)GetDlgItem(IDC_LIST);
CString strFileName;
CString strFileOutput = ExportAsExcel(strFileName, *pList, this);
if (strFileOutput != "")
{
if (AfxMessageBox(strFileOutput + "写入成功\n自动打开吗?", MB_YESNO) == IDYES)
{
ShellExecute(NULL, "open", strFileName.GetBuffer(strFileOutput.GetLength()), NULL, NULL, SW_SHOWNORMAL);
}
}