43.ZIP压缩文件夹
//www.zlib.net
/*
#include <stdio.h>
#include <string.h>
#include <assert.h>
#include <dos.h>
#include <direct.h>
#include <zlib.h>
#if defined(MSDOS) || defined(OS2) || defined(WIN32) ||
defined(__CYGWIN__)
# include <fcntl.h>
# include <io.h>
# define SET_BINARY_MODE(file) setmode(fileno(file),O_BINARY)
#else
# define SET_BINARY_MODE(file)
#endif
#define CHUNK 16384
//#define USE_TAG
#ifdef USE_TAG
#define COMPRESS_FILE_TAG_HEAD "<<<"
#define COMPRESS_FILE_TAG_TAIL ">>>"
#define COMPRESS_FILE_TAG_END_LEN 3 // must be strlen
(COMPRESS_FILE_TAG_HEAD) = strlen(COMPRESS_FILE_TAG_TAIL)
#else
#define COMPRESS_FILE_TAG_HEAD ""
#define COMPRESS_FILE_TAG_TAIL ""
#define COMPRESS_FILE_TAG_END_LEN 0 // must be strlen
(COMPRESS_FILE_TAG_HEAD) = strlen(COMPRESS_FILE_TAG_TAIL)
#endif
*/
/**//**//**//* Compress from file source to file dest until EOF on source.
def() returns Z_OK on success, Z_MEM_ERROR if emory could not be allocated for processing, Z_STREAM_ERROR if an invalid compression
level is supplied, Z_VERSION_ERROR if the version of zlib. And the version of the library linked do not matc, or Z_ERRNO if there isan error reading or writing the files. */
static it def(FILE *source, FILE *dest, int level)
int ret, flush;
unsigned have;
z_stream strm;
unsigned char in[CHUNK];
unsigned char out[CHUNK];
/**//**//**//* allocate deflate state */
strm.zalloc = Z_NULL;
strm.zfree = Z_NULL;
strm.opaque = Z_NULL;
ret = deflateInit(&strm, level);
if (ret != Z_OK)
return ret;
/**//**//**//* compress until end of file */
do {
strm.avail_in = fread(in, 1, CHUNK, source);
if (ferror(source)) {
(void)deflateEnd(&strm);
return Z_ERRNO;
28楼
}
flush = feof(source) ? Z_FINISH : Z_NO_FLUSH;
strm.next_in = in;
/**//**//**//* run deflate() on input until output
buffer not full, finish
compression if all of source has been read in */
do {
strm.avail_out = CHUNK;
strm.next_out = out;
ret = deflate(&strm, flush); /**//**//**//* no
bad return value */
assert(ret != Z_STREAM_ERROR); /**//**//**//*
state not clobbered */
have = CHUNK - strm.avail_out;
if (fwrite(out, 1, have, dest) != have || ferror
(dest)) {
(void)deflateEnd(&strm);
return Z_ERRNO;
}
} while (strm.avail_out == 0);
29楼
assert(strm.avail_in == 0); /**//**//**//* all
input will be used */
/**//**//**//* done when last data in file processed
*/
} while (flush != Z_FINISH);
assert(ret == Z_STREAM_END); /**//**//**//* stream
will be complete */
/**//**//**//* clean up and return */
(void)deflateEnd(&strm);
return Z_OK;
}
/**//**//**//* Decompress from file source to file dest until stream ends or EOF. inf() returns Z_OK on success, Z_MEM_ERROR if memory could not be allocated for processing, Z_DATA_ERROR if the deflate data is invalid or incomplete, Z_VERSION_ERROR if the version of zlib.h and the version of the library linked do not match, or Z_ERRNO
if there is an error reading or writing the files. */
static int inf(FILE *source, FILE *dest)
{
int ret;
unsigned have;
z_stream strm;
unsigned char in[CHUNK];
unsigned char out[CHUNK];
/**//**//**//* allocate inflate state */
strm.zalloc = Z_NULL;
strm.zfree = Z_NULL;
strm.opaque = Z_NULL;
strm.avail_in = 0;
strm.next_in = Z_NULL;
ret = inflateInit(&strm);
if (ret != Z_OK)
return ret;
/**//**//**//* decompress until deflate stream ends or end
of file */
do {
strm.avail_in = fread(in, 1, CHUNK, source);
if (ferror(source)) {
30楼
(void)inflateEnd(&strm);
return Z_ERRNO;
}
if (strm.avail_in == 0)
break;
strm.next_in = in;
/**//**//**//* run inflate() on input until output
buffer not full */
do {
strm.avail_out = CHUNK;
strm.next_out = out;
ret = inflate(&strm, Z_NO_FLUSH);
assert(ret != Z_STREAM_ERROR); /**//**//**//*
state not clobbered */
switch (ret) {
case Z_NEED_DICT:
ret = Z_DATA_ERROR; /**//**//**//* and
fall through */
case Z_DATA_ERROR:
case Z_MEM_ERROR:
(void)inflateEnd(&strm);
return ret;
}
have = CHUNK - strm.avail_out;
if (fwrite(out, 1, have, dest) != have || ferror
(dest)) {
(void)inflateEnd(&strm);
return Z_ERRNO;
31楼
}
} while (strm.avail_out == 0);
/**//**//**//* done when inflate() says it's done */
} while (ret != Z_STREAM_END);
/**//**//**//* clean up and return */
(void)inflateEnd(&strm);
return ret == Z_STREAM_END ? Z_OK : Z_DATA_ERROR;
}
/**//**//**//* report a zlib or i/o error */
static void zerr(int ret)
{
fputs("zpipe: ", stderr);
switch (ret) {
case Z_ERRNO:
if (ferror(stdin))
fputs("error reading stdin ", stderr);
if (ferror(stdout))
fputs("error writing stdout ", stderr);
break;
case Z_STREAM_ERROR:
fputs("invalid compression level ", stderr);
break;
case Z_DATA_ERROR:
fputs("invalid or incomplete deflate data ", stderr);
break;
case Z_MEM_ERROR:
fputs("out of memory ", stderr);
break;
case Z_VERSION_ERROR:
fputs("zlib version mismatch! ", stderr);
}
}
// 以上就是zpipe.c的几个主要函数:def()、inf()和zerr(),def()是压缩函数,主要使用了zlib的deflate()接口;inf()是压缩函数,主要使用了zlib的inflate()接口;zerr()是错误打印函数。
static int write_zfile_file_header(const char *file,FILE *zfile)
{
int len;
len = strlen(file);
if (fwrite(COMPRESS_FILE_TAG_HEAD, 1,COMPRESS_FILE_TAG_END_LEN, zfile) != COMPRESS_FILE_TAG_END_LEN || ferror(zfile))
{
fprintf(stderr,"When writing file or dir header to zfile: write error. ");
return 1;
}
if (fwrite(file, 1, len, zfile) != len|| ferror(zfile))
{
fprintf(stderr,"When writing file or dir header to zfile: write error. ");
return 1;
}
if (fwrite(COMPRESS_FILE_TAG_TAIL, 1,COMPRESS_FILE_TAG_END_LEN, zfile) != COMPRESS_FILE_TAG_END_LEN || ferror(zfile))
{
fprintf(stderr,"When writing file or dir header to
zfile: write error. ");
return 1;
}
return 0;
}
/**//* compress or decompress from stdin to stdout */
static int compress_dir(char *file_in,FILE *fd_out)
{
FILE *fd_in;
struct _finddata_t find_data;
char file[128];
long lf;
int ret;
write_zfile_file_header(file_in,fd_out);
sprintf(file,"%s%s",file_in,"/*");
if((lf = _findfirst(file,&find_data))==-1l) // LOOKOUT:not eleven, but one and lowercase 'L'
{
fprintf(stdout,"file not found. ");
}
else
{
do
{
if(!strcmp(find_data.name,".") || !strcmp(find_data.name,".."))
continue;
fprintf(stdout,"%s",find_data.name);
sprintf(file,"%s%s%s",file_in,"/",find_data.name);
if(find_data.attrib & _A_SUBDIR)
{
fprintf(stdout," ---directory--- ");
ret = compress_dir(file,fd_out);
}
else
{
write_zfile_file_header(file,fd_out);
if(access(file, 2) != 0) //W_OK=2
{
int attrib;
33楼
attrib = _chmod(file,0);
_chmod(file,1,attrib & ~_A_RDONLY);
fprintf(stderr,"When writing file: No privilege to write file %s. ",file);
return -1;
}
fd_in = fopen(file,"rb+");
SET_BINARY_MODE(fd_in);
ret = def(fd_in, fd_out,Z_DEFAULT_COMPRESSION);
if (ret != Z_OK)
zerr(ret);
else
fprintf(stdout," zip over ");
fclose(fd_in);
}
}while( _findnext(lf, &find_data ) == 0 );
}
return 0;
}
//int argc, char **argv
struct _finddata_t find_data;
FILE *fd_in;
FILE *fd_out;
const char *file_dir;
char file_out[100];
int ret;
if (argc == 2)
{
file_dir = argv[1];
if(_findfirst(file_dir,&find_data)==-1l) //LOOKOUT: not eleven, but one and lowercase 'L'
{
fprintf(stderr,"File or dir %s not found.",file_dir);
return 1;
}
if(find_data.attrib & _A_SUBDIR)
{
34楼
sprintf(file_out,"%s%s",file_dir,".z");
fd_out = fopen(file_out,"wb+");
SET_BINARY_MODE(fd_out);
fprintf(stdout,"Dir %s being Compressed ...",file_dir);
ret = compress_dir(file_dir,fd_out);
fclose(fd_out);
}
else
{
fprintf(stdout,"File %s being Compressed ...",file_dir);
sprintf(file_out,"%s%s",file_dir,".z");
fd_in = fopen(file_dir,"rb+");
fd_out = fopen(file_out,"wb+");
SET_BINARY_MODE(fd_in);
SET_BINARY_MODE(fd_out);
ret = def(fd_in, fd_out, Z_DEFAULT_COMPRESSION);
fclose(fd_in);
fclose(fd_out);
}
if (ret != 0)
{
fprintf(stderr,"Compress Error !!!!!!!!!!!!!! ");
zerr(ret);
}
else
fprintf(stdout,"Compress OK--------------- ");
}
else {
fprintf(stdout,"zod usage: zod [file]/[directory] ");
}
getch();
44.验证DTD
/*
#include <stdexcept> // runtime_error
#include <xercesc/sax2/DefaultHandler.hpp>
*/
using namespace std;
using namespace xercesc;
try {
// Initialize Xerces and obtain a SAX2 parser
XercesInitializer init;
auto_ptr<SAX2XMLReader>
parser(XMLReaderFactory::createXMLReader());
// Enable validation
parser->setFeature(XMLUni::fgSAX2CoreValidation, true);
// Register error handler to receive notifications
// of DTD violations
CircusErrorHandler error;
parser->setErrorHandler(&error);
parser->parse("animals.xml");
} catch (const SAXException& e) {
cout << "xml error: " << toNative(e.getMessage()) << "\n";
return EXIT_FAILURE;
} catch (const XMLException& e) {
cout << "xml error: " << toNative(e.getMessage()) << "\n";
return EXIT_FAILURE;
} catch (const exception& e) {
cout << e.what() << "\n";
return EXIT_FAILURE;
}
45.Schema 验证
/*
#include <xercesc/sax2/XMLReaderFactory.hpp>
#include <xercesc/sax2/SAX2XMLReader.hpp>
#include <xercesc/sax2/DefaultHandler.hpp>
Handy definitions of constants.
#include <xercesc/util/XMLUni.hpp>
Create a SAX2 parser object.
*/
SAX2XMLReader* parser = XMLReaderFactory::createXMLReader();
// Set the appropriate features on the parser. Enable namespaces, schema validation, and the checking of all Schema
constraints. We refer to these as "common features" in following examples.
parser->setFeature(XMLUni::fgSAX2CoreNameSpaces, true);
parser->setFeature(XMLUni::fgSAX2CoreValidation, true);
parser->setFeature(XMLUni::fgXercesDynamic, false);
parser->setFeature(XMLUni::fgXercesSchema, true);
parser->setFeature(XMLUni::fgXercesSchemaFullChecking, true);
// Set appropriate ContentHandler, ErrorHandler, and EntityResolver.
// These will be referred to as "common handlers" in subsequent examples.
// You will use a default handler provided by Xerces-C++ (no op action).
// Users should write their own handlers and install them.
DefaultHandler handler;
parser->setContentHandler(&handler);
// The object parser calls when it detects violations of the schema.
parser->setErrorHandler(&handler);
// The object parser calls to find the schema and
// resolve schema imports/includes.
parser->setEntityResolver(&handler);
// Parse the XML document.
// Document content sent to registered ContentHandler instance.
parser->parse(xmlFile);
// Delete the parser instance.
delete parser;
46.Grep
/*
#include<string>
#include "regexpr2.h"
using namespace std;
using namespace regex;
*/
match_results results;
rpattern pat(%%2);
char sRead[5120];
CFile mFile(_T(%%1),CFile::modeRead);
CString content;
while(sRead!=NULL)
{
mFile.Read(sRead,5120);
content+=CString(sRead);
}
mFile.Close();
CString line;
CString sub;
char seperator='\n';
for(int pos=0;AfxExtractSubString(line,content,pos,seperator);++pos)
{
if(line.Trim()!="")
{
string str(line);
match_results::backref_type br=pat.match(str,results);
if(br.matched){
//br
}
}
}
47.直接创建多级目录
typedef BOOL (__stdcall funMakeSure(LPCSTR DirPath));
funMakeSure *MakeSureDirectoryPathExists;
HMODULE hMod=LoadLibrary("dbghelp.dll");
MakeSureDirectoryPathExists(*funMakeSure)GetProcAddress(hMod,"MakeSureDirectoryPathExists");
MakeSureDirectoryPathExists(%%1);
48.批量重命名
CString strPath,strFilter,srcTitle,src,srcFile,dstFile,dstFileTitle;
int i=1,iFileNum=1;
CFile myFile,newFile;
//获取将要批量处理的文件夹及文件格式
strPath=%%1;
strFilter=%%2;
//判断文件夹是否为空
if(strPath.IsEmpty())
{
MessageBox("请先选择要重命名文件所在文件夹!","警告!");
return;
}
//在该文件夹内创建目录文件
src=strPath+"*."+strFilter;
CString list=strPath+"目录.txt";
if(myFile.Open(list,CFile::modeCreate|CFile::modeReadWrite,0) ==0) return;
CFileFind tempFind;
BOOL isFound=(BOOL)tempFind.FindFile(src);
//确定该文件夹内要处理的有多少个文件
while(isFound)
{
isFound=(BOOL)tempFind.FindNextFile();
if(tempFind.IsDirectory())
{
continue;
}
iFileNum++;
}
//进行文件名的转换,以文件数定转换后的文件名,如果有9个文件,则以1-9的形式命名,如果是更多,如有99个文件,则为01-99的形式
isFound=(BOOL)tempFind.FindFile(src);
while(isFound && i<iFileNum)
{
isFound=(BOOL)tempFind.FindNextFile();
if(tempFind.IsDirectory())
{
continue;
}
srcFile=tempFind.GetFilePath();
srcTitle=tempFind.GetFileTitle();
if(iFileNum<10)
{
dstFileTitle.Format("%d",i);
}
else if(iFileNum<100 && iFileNum>9)
{
dstFileTitle.Format("%02d",i);
}
else if(iFileNum<1000 && iFileNum>99)
{
dstFileTitle.Format("%03d",i);
}
else if(iFileNum<10000 && iFileNum>999)
{
dstFileTitle.Format("%04d",i);
}
else if(iFileNum<100000 && iFileNum>9999)
{
dstFileTitle.Format("%05d",i);
}
else
{
dstFileTitle.Format("%d",i);
}
//实现转换
dstFile=strPath+dstFileTitle+"."+strFilter;
MoveFile(srcFile,dstFile);
//存入目录文件中
CString in;
in=dstFileTitle+'\t'+srcTitle+"\t\r\n";
myFile.Write(in,in.GetLength());
i++;
SetWindowText(srcFile);
}
//关闭myFile,tempFind
myFile.Close();
tempFind.Close();
49.文本查找替换 ReplaceText
CString StrFileName(%%1);
CString StrFind(%%2);
CString StrReplace(%%3);
CStdioFile TempFile,File;
int Count=0;
if(!File.Open(StrFileName,CFile::modeRead))
return -1;
CString StrTempFileName=File.GetFileTitle()+".tmp";
if(!TempFile.Open(StrTempFileName,CFile::modeCreate|CFile::modeReadWrite))
return -1;
CString Str;
while(File.ReadString(Str))
{
Count+=Str.Replace(StrFind,StrReplace);
TempFile.WriteString(Str+"\n");
}
File.Close();
TempFile.Close();
CFile::Remove(StrFileName);
CFile::Rename(StrTempFileName,StrFileName);
//return Count;
50.文件关联
//---------------------------------------------------------------------------
// 检测文件关联情况
// strExt: 要检测的扩展名(例如: ".txt")
// strAppKey: ExeName扩展名在注册表中的键值(例如: "txtfile")
// 返回TRUE: 表示已关联,FALSE: 表示未关联
BOOL CheckFileRelation(const char *strExt, const char *strAppKey)
{
int nRet=FALSE;
HKEY hExtKey;
char szPath[_MAX_PATH];
DWORD dwSize=sizeof(szPath);
if(RegOpenKey(HKEY_CLASSES_ROOT,strExt,&hExtKey)==ERROR_SUCCESS)
{
RegQueryValueEx(hExtKey,NULL,NULL,NULL,(LPBYTE)szPath,&dwSize);
if(_stricmp(szPath,strAppKey)==0)
{
nRet=TRUE;
}
RegCloseKey(hExtKey);
return nRet;
}
return nRet;
}
//---------------------------------------------------------------------------
// 注册文件关联
// strExe: 要检测的扩展名(例如: ".txt")
// strAppName: 要关联的应用程序名(例如: "C:\MyApp\MyApp.exe")
// strAppKey: ExeName扩展名在注册表中的键值(例如: "txtfile")
// strDefaultIcon: 扩展名为strAppName的图标文件(例如: "C:\MyApp\MyApp.exe,0")
// strDescribe: 文件类型描述
void RegisterFileRelation(char *strExt, char *strAppName, char *strAppKey, char *strDefaultIcon, char
*strDescribe)
{
char strTemp[_MAX_PATH];
HKEY hKey;
RegCreateKey(HKEY_CLASSES_ROOT,strExt,&hKey);
RegSetValue(hKey,"",REG_SZ,strAppKey,strlen(strAppKey)+1);
RegCloseKey(hKey);
RegCreateKey(HKEY_CLASSES_ROOT,strAppKey,&hKey);
RegSetValue(hKey,"",REG_SZ,strDescribe,strlen(strDescribe)+1);
RegCloseKey(hKey);
sprintf(strTemp,"%s\\DefaultIcon",strAppKey);
RegCreateKey(HKEY_CLASSES_ROOT,strTemp,&hKey);
RegSetValue(hKey,"",REG_SZ,strDefaultIcon,strlen(strDefaultIcon)+1);
RegCloseKey(hKey);
sprintf(strTemp,"%s\\Shell",strAppKey);
RegCreateKey(HKEY_CLASSES_ROOT,strTemp,&hKey);
RegSetValue(hKey,"",REG_SZ,"Open",strlen("Open")+1);
RegCloseKey(hKey);
sprintf(strTemp,"%s\\Shell\\Open\\Command",strAppKey);
RegCreateKey(HKEY_CLASSES_ROOT,strTemp,&hKey);
sprintf(strTemp,"%s \"%%1\"",strAppName);
RegSetValue(hKey,"",REG_SZ,strTemp,strlen(strTemp)+1);
RegCloseKey(hKey);
}
42楼
51.操作Excel文件
//#include "excel.h"
//#include "COMDEF.H"
char ch[200];
GetCurrentDirectory(200,ch);
sCCdd=ch;
GetSystemDirectory(ch,200);
sXTdd=ch;
CString ss;
ss.Format("%s\\txl.mdb",sCCdd);
if(!LoadDbSource("vcexcel",ss,""))
{
// EndDialog(0);
return FALSE;
}
m_list.SetBkColor(RGB(177, 151, 240));
m_list.SetTextColor(RGB(0,0,0));
m_list.SetTextBkColor(RGB(177, 151, 240));
m_list.SetExtendedStyle(LVS_EX_FULLROWSELECT|LVS_EX_GRIDLINES|LVS_EX_HEADERDRAGDROP);
m_pSet=new CTxl;
ShowTxl();
void OnButton1()
{
/* 添加*/
CString strSQL;
CTjdlg dlg;
if(dlg.DoModal()==IDOK)
{
strSQL.Format("insert into 通信录 (姓名,单位,电话,手机,地址) values ('%s','%s','%s','%s','%
s')",dlg.m_strXm,dlg.m_strDw,dlg.m_strDh,dlg.m_strSj,dlg.m_strDz);
m_pSet->m_pDatabase->ExecuteSQL(strSQL);
ShowTxl();//显示通信录
}
}
void OnButton2()
{
/*删除*/
int isel;
CString str,strSQL;
CTjdlg dlg;
isel=m_list.GetSelectedCount();
if(isel==0)
{
AfxMessageBox("请先选择一条记录");
return;
}
isel=m_list.GetNextItem(-1,LVNI_SELECTED);
str=m_list.GetItemText(isel,0);
strSQL.Format("你确实要删除姓名为'%s'的记录吗?",str);
if(AfxMessageBox(strSQL,MB_YESNO)==IDYES)
{
strSQL.Format("delete * from 通信录 where 姓名='%s'",str);
try
{
m_pSet->m_pDatabase->BeginTrans();
m_pSet->m_pDatabase->ExecuteSQL(strSQL);
m_pSet->m_pDatabase->CommitTrans();
}
catch(CException*pE)
{
m_pSet->m_pDatabase->Rollback();
pE->Delete();
}
strSQL.Format("已成功删除姓名为'%s'的记录!",str);
AfxMessageBox(strSQL);
ShowTxl();//显示通信录
}
}
void OnButton3()
{
/*修改 */
int isel;
CString str,strSQL;
CTjdlg dlg;
isel=m_list.GetSelectedCount();
if(isel==0)
{
AfxMessageBox("请先选择一条记录");
return;
}
isel=m_list.GetNextItem(-1,LVNI_SELECTED);
str=m_list.GetItemText(isel,0);
dlg.m_bXg=true;
strSQL.Format("select * from 通信录 where 姓名='%s'",str);
if(m_pSet->IsOpen())
m_pSet->Close();
m_pSet->Open(CRecordset::dynaset, strSQL);
if(!(m_pSet->IsEOF()))
{
m_pSet->GetFieldValue((short)0,dlg.m_strXm);
m_pSet->GetFieldValue(1,dlg.m_strDw);
m_pSet->GetFieldValue(2,dlg.m_strDh);
m_pSet->GetFieldValue(3,dlg.m_strSj);
m_pSet->GetFieldValue(4,dlg.m_strDz);
}
if(dlg.DoModal()==IDOK)
{
strSQL.Format("update 通信录 set 姓名='%s',单位='%s',电话='%s',手机='%s',地址='%s' where 姓名='%s'",
dlg.m_strXm,dlg.m_strDw,dlg.m_strDh,dlg.m_strSj,dlg.m_strDz,str);
m_pSet->m_pDatabase->ExecuteSQL(strSQL);
ShowTxl();//显示通信录
}
}
void OnButton4()
{
/*导出到 excel 文档*/
CString sss,s1,s2,e1,e2,strSQL;
CStringArray sa;
static char szFilter[] = "EXCEL Files(*.xls)|*.xls||";
CTxl rs;
strSQL.Format("select * from 通信录");
44楼
rs.Open(CRecordset::dynaset, strSQL);//打开通信录
CString fname,fname1, sheetname,s;
CFileDialog FileDlg( FALSE, NULL, NULL,OFN_HIDEREADONLY, szFilter );
if( FileDlg.DoModal() != IDOK ||FileDlg.GetPathName()=="")
{
return;//打开另存对话框,如果文件名为空或打开不成功则返回
}
fname=FileDlg.GetPathName();//得到要导出保存的路径及文件名
/*定义操作Execl的对象*/
_Application objApp;
Workbooks objBooks;
_Workbook objBook;
Sheets objSheets;
_Worksheet objSheet;
Range objRange,objRange1,objRange2;
Lines objLines;
Line objLine;
Borders objBorders;
Font oFont;
COleVariant covOptional((long)DISP_E_PARAMNOTFOUND, VT_ERROR);
COleVariant covTrue((short)TRUE), covFalse((short)FALSE),\
varFormat((short)-4143),varCenter((short)-4108),varLeft((short)-4131),varText("TEXT",VT_BSTR),var,\
varRange1("A1",VT_BSTR),varRange2("D1",VT_BSTR);
//初始化COM 组件
::CoInitialize(NULL);
//创建Excel对象
objApp.m_bAutoRelease=true;
if(!objApp.CreateDispatch("Excel.Application"))
{
AfxMessageBox("创建Excel服务失败!");
return;
}
objBooks=objApp.GetWorkbooks(); //返回工作簿对象
// 打开Excel文件n
objBook.AttachDispatch(objBooks.Add(_variant_t("")));//C:\\lb.xls
objSheets=objBook.GetSheets();
// 定义第一个Sheet为对象
objSheet=objSheets.GetItem((_variant_t)short(1));
sheetname="通讯录";
objSheet.SetName(sheetname);//将第一个工作表名称设为"通讯录"//
objSheet.Activate();
objRange.AttachDispatch(objSheet.GetCells(),true);
objLine.AttachDispatch(objSheet.GetCells(),true);
objApp.SetVisible(true);//设置为显示
int nn=2,syh=0,nFieldcnt;
char cc='A';
45楼
s1.Format("B%d",nn);
nFieldcnt=rs.GetODBCFieldCount();
CODBCFieldInfo fieldinfo;
for(int n=0;n<nFieldcnt;n++,cc++)
{
/*将字段名作为标题导出到execl的第一行*/
rs.GetODBCFieldInfo(n, fieldinfo);
s1.Format("%c1",cc);
objRange1=objSheet.GetRange(_variant_t(s1),_variant_t(s1));
objRange1.SetHorizontalAlignment(varCenter);
objRange1.SetVerticalAlignment(varCenter);
oFont=objRange1.GetFont();
oFont.SetBold(_variant_t((long)1));//设为粗体
objRange1.SetFormulaR1C1(_variant_t(fieldinfo.m_strName));
objRange1.SetColumnWidth(_variant_t("20"));
objBorders=objRange1.GetBorders();
objBorders.SetLineStyle(_variant_t((long)1));
}
/
rs.MoveFirst();
while(!rs.IsEOF())
{
/*将通讯录中数据导出到excel单元格中*/
sa.RemoveAll();
for(int j=0;j<nFieldcnt;j++)
{
rs.GetFieldValue(j, s);
sa.Add(s);
}
s1.Format("A%d",nn);
e1=s1;
objRange1=objSheet.GetRange(_variant_t(s1),_variant_t(s1));
s="'";
s+=sa.GetAt(0);
objRange1.SetFormulaR1C1(_variant_t(s));
objBorders=objRange1.GetBorders();
objBorders.SetLineStyle(_variant_t((long)1));
s1.Format("B%d",nn);
objRange1=objSheet.GetRange(_variant_t(s1),_variant_t(s1));
s=sa.GetAt(1);
objRange1.SetFormulaR1C1(_variant_t(s));
objBorders=objRange1.GetBorders();
objBorders.SetLineStyle(_variant_t((long)1));
s1.Format("C%d",nn);
objRange1=objSheet.GetRange(_variant_t(s1),_variant_t(s1));
s=sa.GetAt(2);
objRange1.SetFormulaR1C1(_variant_t(s));
objBorders=objRange1.GetBorders();
objBorders.SetLineStyle(_variant_t((long)1));
s1.Format("D%d",nn);
objRange1=objSheet.GetRange(_variant_t(s1),_variant_t(s1));
s=sa.GetAt(3);
objRange1.SetFormulaR1C1(_variant_t(s));
objBorders=objRange1.GetBorders();
objBorders.SetLineStyle(_variant_t((long)1));
s1.Format("E%d",nn);
e2=s1;
objRange1=objSheet.GetRange(_variant_t(s1),_variant_t(s1));
s=sa.GetAt(4);
objRange1.SetFormulaR1C1(_variant_t(s));
objBorders=objRange1.GetBorders();
objBorders.SetLineStyle(_variant_t((long)1));
if(sa.GetAt(4).Find("和平")!=-1)
{
/*如果地址字段中含有"和平",则该纪录字体设为粗体斜体和蓝色*/
objRange1=objSheet.GetRange(_variant_t(e1),_variant_t(e2));
oFont=objRange1.GetFont();
oFont.SetBold(_variant_t((short)1));
oFont.SetItalic(_variant_t((short)1));
oFont.SetColor(_variant_t((long)0xFF0000));
}
nn++;
rs.MoveNext();
}
rs.Close();
/*设置打印信息*/
PageSetup PageInfo=objSheet.GetPageSetup();
//描述页眉信息:楷体 20号字体
CString HeaderFormat= "&";
HeaderFormat+="\"楷体_GB2312,常规\"";
HeaderFormat+="&20通信录";
PageInfo.SetCenterHeader(HeaderFormat);
//设置页脚信息:楷体 12号字体
CString FooterFormat= "&";
FooterFormat+="\"楷体_GB2312,常规\"";
FooterFormat+="&12第";
//"&p":页码
FooterFormat+="&p";
FooterFormat+="页";
FooterFormat+=" 共";
FooterFormat+="&n";
FooterFormat+="页";
PageInfo.SetCenterFooter(FooterFormat); //设置页脚
PageInfo.SetOrientation(2); //横向打印
PageInfo.SetPaperSize(9); //设置纸张大小为A4
PageInfo.SetFirstPageNumber(-4105);//第一页编号为默认值1
PageInfo.SetPrintTitleRows("$1:$1"); //设置标题行
PageInfo.SetZoom(COleVariant((short)100)); //设置打印缩放比例100%
PageInfo.SetCenterHorizontally(1); //水平居中
PageInfo.SetCenterVertically(0); //垂直居中
//进行打印预览,允许用户进行打印参数修改
//objSheet.PrintPreview(COleVariant((short)1));
objBook.SaveAs(_variant_t
(fname),varFormat,covOptional,covOptional,covOptional,covOptional,0,covOptional,covOptional,covOptional,covOptional
,covOptional);
objApp.Quit();
objRange.ReleaseDispatch();
objSheet.ReleaseDispatch();
objSheets.ReleaseDispatch();
objBook.ReleaseDispatch();
objBooks.ReleaseDispatch();
//保存,退出及释放定义的Excel对象
::CoUninitialize();//取消COM组件的初始化
s.Format("已成功地将数据导出到EXCEL文件'%s'中",fname);
48楼
AfxMessageBox(s);
}
bool ShowTxl()
{
/*显示通讯录*/
CString strSQL="select * from 通信录";
while(m_list.DeleteColumn(0));
m_list.DeleteAllItems();
try{
if(m_pSet->IsOpen())m_pSet->Close();
m_pSet->Open(CRecordset::dynaset, strSQL);
if(!m_pSet->IsEOF())
{
m_pSet->MoveLast();
m_pSet->MoveFirst();
}
else
{
return FALSE;
}
int nFieldCount = m_pSet->GetODBCFieldCount();
CODBCFieldInfo fieldinfo;
for(int n=0;n<nFieldCount;n++)
{
m_pSet->GetODBCFieldInfo(n, fieldinfo);
int nWidth = m_list.GetStringWidth(fieldinfo.m_strName) +80;
m_list.InsertColumn(n, fieldinfo.m_strName, LVCFMT_LEFT, nWidth);
}
CString strValue;
m_pSet->MoveFirst();
int nCount = 0;
while(!m_pSet->IsEOF())
{
m_list.InsertItem(nCount, strValue);
for(int j=0;j<nFieldCount;j++)
{
m_pSet->GetFieldValue(j, strValue);
m_list.SetItemText(nCount, j, strValue);
}
m_pSet->MoveNext();
nCount ++;
}
}
catch(CDBException *e)
{
e->ReportError();
return FALSE;
}
return TRUE;
}
void OnDblclkList1(NMHDR* pNMHDR, LRESULT* pResult)
{
/* 双击列表视图修改记录*/
OnButton3();
*pResult = 0;
}
BOOL LoadDbSource(
CString strSourceName, //数据源名
CString strSourceDb, //数据库存放路径
CString strDescription //数据源描述字符串
)
{
HKEY hKey;
DWORD lDisp;
CString ss;//sold="\\",snew="\\\";
//注册数据源名
CString strSubKey="SOFTWARE\\ODBC\\ODBC.INI\\"+strSourceName;
// RegCreateKeyEx(HKEY_LOCAL_MACHINE,
RegCreateKeyEx(HKEY_CURRENT_USER,
strSubKey,
0,
NULL,
REG_OPTION_NON_VOLATILE,
KEY_ALL_ACCESS,
NULL,
&hKey,
&lDisp);
//注册ODBC驱动程序
CString value1; //("E:\\WINDOWS\\System32\\odbcjt32.dll");
ss=sXTdd;
value1.Format("%s\\odbcjt32.dll",ss);
// AfxMessageBox(value1);
RegSetValueEx(hKey,
"Driver",
0,
REG_SZ,
(const unsigned char *)((LPCTSTR)value1),
strlen((LPCTSTR)value1)+1);
//注册数据库文件
CString value2 = strSourceDb;
RegSetValueEx(hKey,
"DBQ",
0,
REG_SZ,
(const unsigned char *)((LPCTSTR)value2),
strlen((LPCTSTR)value2)+1);
DWORD value3=(DWORD)25;
RegSetValueEx(hKey,
"DriverID",
0,
REG_DWORD,
(const BYTE *)&value3,
sizeof(DWORD));
CString value4("Ms Access");
RegSetValueEx(hKey,
"FIL",
0,
REG_SZ,
(const unsigned char *)((LPCTSTR)value4),
strlen((LPCTSTR)value4)+1);
DWORD value5=(DWORD)0;
RegSetValueEx(hKey,
"SafeTransactions",
0,
REG_DWORD,
(const BYTE *)&value5,
sizeof(DWORD));
CString value6("");
RegSetValueEx(hKey,
"UID",
0,
REG_SZ,
(const unsigned char *)((LPCTSTR)value6),
strlen((LPCTSTR)value6)+1);
return TRUE;
}
void OnButton5()
{
/*从Excel导入*/
CString s1,s2,strSQL;
CStringArray sa;
static char szFilter[] = "EXCEL Files(*.xls)|*.xls||";
CTxl rs;
rs.Open();
CString fname,fname1, sheetname,s;
CFileDialog FileDlg( TRUE, NULL, NULL,
OFN_HIDEREADONLY, szFilter );
if( FileDlg.DoModal() != IDOK ||
FileDlg.GetPathName()=="")
{
return;//打开打开对话框,如果文件名为空或打开不成功则返回
}
fname=FileDlg.GetPathName();//得到要导入的Excel文件的路径及文件名
/*定义操作Execl的对象*/
_Application objApp;
Workbooks objBooks;
_Workbook objBook;
Sheets objSheets;
_Worksheet objSheet;
Range objRange,objRange1,objRange2;
Lines objLines;
Line objLine;
Borders objBorders;
COleVariant covOptional((long)DISP_E_PARAMNOTFOUND, VT_ERROR);
COleVariant covTrue((short)TRUE), covFalse((short)FALSE),\
varFormat((short)-4143),varCenter((short)-4108),varLeft((short)-4131),varText("TEXT",VT_BSTR),var,\
varRange1("A1",VT_BSTR),varRange2("D1",VT_BSTR);
//初始化COM 组件
::CoInitialize(NULL);
//创建Excel对象
objApp.m_bAutoRelease=true;
if(!objApp.CreateDispatch("Excel.Application"))
{
AfxMessageBox("创建Excel服务失败!");
return;
}
objBooks=objApp.GetWorkbooks(); //返回工作簿对象
// 打开Excel文件
objBook.AttachDispatch(objBooks.Add(_variant_t(fname)));
objSheets=objBook.GetSheets();
// 选择Excel文件的第一个工作表
objSheet=objSheets.GetItem((_variant_t)short(1));
objRange.AttachDispatch(objSheet.GetCells(),true);
objLine.AttachDispatch(objSheet.GetCells(),true);
//将数据库的通信录表置空
strSQL.Format("delete * from 通信录");
rs.m_pDatabase->ExecuteSQL(strSQL);
int nn=2;
char cc='A';
s1.Format("A%d",nn);
objRange1=objApp.GetRange(_variant_t(s1),_variant_t(s1));
var=objRange1.GetFormulaR1C1();
s=var.bstrVal;
BeginWaitCursor();
while(s!="")
{ //将Excel文件中数据导入到数据库的通信录表中
sa.RemoveAll();
s1.Format("A%d",nn);
objRange1=objApp.GetRange(_variant_t(s1),_variant_t(s1));
var=objRange1.GetFormulaR1C1();//GetText();//GetFormulaR1C1();
s=var.bstrVal;
sa.Add(s);
s1.Format("B%d",nn);
objRange1=objApp.GetRange(_variant_t(s1),_variant_t(s1));
var=objRange1.GetFormulaR1C1();
s=var.bstrVal;
s2=s;
sa.Add(s);
s1.Format("C%d",nn);
objRange1=objApp.GetRange(_variant_t(s1),_variant_t(s1));
var=objRange1.GetFormulaR1C1();
s=var.bstrVal;
sa.Add(s);
s1.Format("D%d",nn);
objRange1=objApp.GetRange(_variant_t(s1),_variant_t(s1));
var=objRange1.GetFormulaR1C1();
s=var.bstrVal;
sa.Add(s);
s1.Format("E%d",nn);
objRange1=objApp.GetRange(_variant_t(s1),_variant_t(s1));
var=objRange1.GetFormulaR1C1();
s=var.bstrVal;
sa.Add(s);
strSQL.Format("INSERT INTO 通信录 ( 姓名,单位,电话,手机,地址)\
VALUES ('%s', '%s', '%s','%s','%s')",sa.GetAt(0),sa.GetAt(1),sa.GetAt(2),sa.GetAt(3),sa.GetAt(4));
rs.m_pDatabase->ExecuteSQL(strSQL);
nn++;
s1.Format("A%d",nn);
objRange1=objApp.GetRange(_variant_t(s1),_variant_t(s1));
var=objRange1.GetFormulaR1C1();
s=var.bstrVal;
}
rs.Close();
EndWaitCursor();
objApp.Quit();
objRange.ReleaseDispatch();
objSheet.ReleaseDispatch();
objSheets.ReleaseDispatch();
objBook.ReleaseDispatch();
objBooks.ReleaseDispatch();
//退出及释放定义的Excel对象
::CoUninitialize();//取消COM组件的初始化
s.Format("已成功地将数据从EXCEL文件'%s'导入到数据库",fname);
AfxMessageBox(s);
ShowTxl();//显示通信录
}