您的位置:首页 > 其它

VC实现EXCEL转换为CSV格式

2007-11-14 11:52 525 查看
/************************************************************************
*函数名称:ConverXLSToCSV
*功能描述:打开EXCEL文件,并转存为CSV格式文件
*输入参数:pSrcFileName ,源文件;pDesFileName,目标文件
*输出参数:无
*返回结果:S_OK,成功;S_FALSE,失败
*特别说明:无
*************************************************************************/
HRESULT ConverXLSToCSV(const char *pSrcFileName, const char *pDesFileName)
{
//单线程方式创建COM对象
::CoInitialize(0);
if(1)
{
//初始化EXCEL对象
CComDispatchDriver execlAppDsp;
HRESULT hr = execlAppDsp.CoCreateInstance(L"Excel.Application", 0, CLSCTX_LOCAL_SERVER|CLSCTX_INPROC_SERVER);
//获取工作页,打开XLS文件
CComVariant vWorkbooks;
hr = execlAppDsp.GetPropertyByName(L"Workbooks", &vWorkbooks);
CComDispatchDriver booksDsp(vWorkbooks.pdispVal);
CComVariant vSrcFileName(pSrcFileName);
hr = booksDsp.Invoke1(L"Open", &vSrcFileName);
//关闭警告对话框
CComVariant vDisplay(L"FALSE");
hr = execlAppDsp.PutPropertyByName(L"DisplayAlerts", &vDisplay);
//打开活动页,另存为CSV文件
CComVariant vActBook;
hr = execlAppDsp.GetPropertyByName(L"ActiveWorkbook", &vActBook);
CComDispatchDriver activeBookDsp(vActBook.pdispVal);
CComVariant vDesFileName(pDesFileName);
CComVariant vFileType("6");
hr = activeBookDsp.Invoke2(L"SaveAs", &vDesFileName, &vFileType);
//关闭EXCEL
execlAppDsp.Invoke0(L"Quit");
}
//释放
::CoUninitialize();

return S_OK;
}

国外查找的一源文件如下:

// ExcelCom.h: interface for the ExcelCom class.
//
//////////////////////////////////////////////////////////////////////

#if !defined(AFX_EXCELCOM_H__E1613E65_0F18_454E_B424_64476E091C7C__INCLUDED_)
#define AFX_EXCELCOM_H__E1613E65_0F18_454E_B424_64476E091C7C__INCLUDED_

#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000

#include <atlbase.h>
extern CComModule _Module;
#include <atlcom.h>

#include <DBTime.h>

class ExcelCom : public CComDispatchDriver
{
bool m_Valid;

public:

CString sCell(int aRow, int aCol);
VARIANT vCell(int aRow, int aCol);
bool PutStr(int aRow, int aCol, const char *aStr);
bool Close();

enum XlWindowState
{
xlMaximized = -4137,
xlMinimized = -4140,
xlNormal = -4143
};

enum XlBordersIndex
{
xlInsideHorizontal = 12,
xlInsideVertical = 11,
xlDiagonalDown = 5,
xlDiagonalUp = 6,
xlEdgeBottom = 9,
xlEdgeLeft = 7,
xlEdgeRight = 10,
xlEdgeTop = 8
} ;

enum XlLineStyle
{
xlContinuous = 1,
xlDash = -4115,
xlDashDot = 4,
xlDashDotDot = 5,
xlDot = -4118,
xlDouble = -4119,
xlSlantDashDot = 13,
xlLineStyleNone = -4142
} ;

enum XlBorderWeight
{
xlHairline = 1,
xlMedium = -4138,
xlThick = 4,
xlThin = 2
} ;

enum Constants
{
xlAll = -4104,
xlAutomatic = -4105,
xlBoth = 1,
xlCenter = -4108,
xlChecker = 9,
xlCircle = 8,
xlCorner = 2,
xlCrissCross = 16,
xlCross = 4,
xlDiamond = 2,
xlDistributed = -4117,
xlDoubleAccounting = 5,
xlFixedValue = 1,
xlFormats = -4122,
xlGray16 = 17,
xlGray8 = 18,
xlGrid = 15,
xlHigh = -4127,
xlInside = 2,
xlJustify = -4130,
xlLightDown = 13,
xlLightHorizontal = 11,
xlLightUp = 14,
xlLightVertical = 12,
xlLow = -4134,
xlManual = -4135,
xlMinusValues = 3,
xlModule = -4141,
xlNextToAxis = 4,
xlNone = -4142,
xlNotes = -4144,
xlOff = -4146,
xlOn = 1,
xlPercent = 2,
xlPlus = 9,
xlPlusValues = 2,
xlSemiGray75 = 10,
xlShowLabel = 4,
xlShowLabelAndPercent = 5,
xlShowPercent = 3,
xlShowValue = 2,
xlSimple = -4154,
xlSingle = 2,
xlSingleAccounting = 4,
xlSolid = 1,
xlSquare = 1,
xlStar = 5,
xlStError = 4,
xlToolbarButton = 2,
xlTriangle = 3,
xlGray25 = -4124,
xlGray50 = -4125,
xlGray75 = -4126,
xlBottom = -4107,
xlLeft = -4131,
xlRight = -4152,
xlTop = -4160,
xl3DBar = -4099,
xl3DSurface = -4103,
xlBar = 2,
xlColumn = 3,
xlCombination = -4111,
xlCustom = -4114,
xlDefaultAutoFormat = -1,
xlMaximum = 2,
xlMinimum = 4,
xlOpaque = 3,
xlTransparent = 2,
xlBidi = -5000,
xlLatin = -5001,
xlContext = -5002,
xlLTR = -5003,
xlRTL = -5004,
xlFullScript = 1,
xlPartialScript = 2,
xlMixedScript = 3,
xlMixedAuthorizedScript = 4,
xlVisualCursor = 2,
xlLogicalCursor = 1,
xlSystem = 1,
xlPartial = 3,
xlHindiNumerals = 3,
xlBidiCalendar = 3,
xlGregorian = 2,
xlComplete = 4,
xlScale = 3,
xlClosed = 3,
xlColor1 = 7,
xlColor2 = 8,
xlColor3 = 9,
xlConstants = 2,
xlContents = 2,
xlBelow = 1,
xlCascade = 7,
xlCenterAcrossSelection = 7,
xlChart4 = 2,
xlChartSeries = 17,
xlChartShort = 6,
xlChartTitles = 18,
xlClassic1 = 1,
xlClassic2 = 2,
xlClassic3 = 3,
xl3DEffects1 = 13,
xl3DEffects2 = 14,
xlAbove = 0,
xlAccounting1 = 4,
xlAccounting2 = 5,
xlAccounting3 = 6,
xlAccounting4 = 17,
xlAdd = 2,
xlDebugCodePane = 13,
xlDesktop = 9,
xlDirect = 1,
xlDivide = 5,
xlDoubleClosed = 5,
xlDoubleOpen = 4,
xlDoubleQuote = 1,
xlEntireChart = 20,
xlExcelMenus = 1,
xlExtended = 3,
xlFill = 5,
xlFirst = 0,
xlFloating = 5,
xlFormula = 5,
xlGeneral = 1,
xlGridline = 22,
xlIcons = 1,
xlImmediatePane = 12,
xlInteger = 2,
xlLast = 1,
xlLastCell = 11,
xlList1 = 10,
xlList2 = 11,
xlList3 = 12,
xlLocalFormat1 = 15,
xlLocalFormat2 = 16,
xlLong = 3,
xlLotusHelp = 2,
xlMacrosheetCell = 7,
xlMixed = 2,
xlMultiply = 4,
xlNarrow = 1,
xlNoDocuments = 3,
xlOpen = 2,
xlOutside = 3,
xlReference = 4,
xlSemiautomatic = 2,
xlShort = 1,
xlSingleQuote = 2,
xlStrict = 2,
xlSubtract = 3,
xlTextBox = 16,
xlTiled = 1,
xlTitleBar = 8,
xlToolbar = 1,
xlVisible = 12,
xlWatchPane = 11,
xlWide = 3,
xlWorkbookTab = 6,
xlWorksheet4 = 1,
xlWorksheetCell = 3,
xlWorksheetShort = 5,
xlAllExceptBorders = 7,
xlLeftToRight = 2,
xlTopToBottom = 1,
xlVeryHidden = 2,
xlDrawingObject = 14
};

ExcelCom();
ExcelCom* operator&() {return this; }

bool WindowState(XlWindowState ws);
bool OpenFile(CString FName);
bool SaveFileAs(CString FName);
bool CloseAllBooks();

void SetVisible(bool bVisible = true);

bool Init();
bool Restore();
bool Minimiz() { return WindowState(xlMinimized);};
bool Maximiz() { return WindowState(xlMaximized);};

bool PutRange(int aRow, int aCol, CComVariant arg1);

bool PutDoub (int aRow, int aCol, double aArg, int prec=0);
bool PutDate (int aRow, int aCol, DBTime aArg);
bool PutInt (int aRow, int aCol, long aArg);
bool PutFormula(int aRow, int aCol, CString aFormula);

// несколько команд
bool ExecVbaSrc(CString cmd, int aRow = 0);
// выполнить команду на басике
int xlConst(CString xl);
bool ExecBasLine(CString cmd);
bool ExecBasLine(VARIANT &value, CString cmd);
bool RunFunc(IDispatch* p, CString Name);
bool SetProp(IDispatch* p, CString PropName, CString Val);
bool GetPureName(CString Name, CString &PureName, VARIANT &arg);
CComVariant GetProp(IDispatch* p, CString PropName);

// интерфейс для работы с листами Exceell
bool AddNewList();
bool RenameList(CString ListName);
bool DeleteList(CString ListName);
bool SelectList(CString ListName);
bool DeleteList(int ListNum);
bool SelectList(int ListNum);
CString GetListName();
int GetListCount();

// дополнительные возможности
bool SetColumeWidth( int Col , int Width);
bool SetBold ( int Row , int Col);
bool SetBoldLine ( int Row);
bool SetBoldColum ( int Col);
bool SetItalic ( int Row , int Col);
bool SetItalicLine ( int Row);
bool SetItalicColum( int Col);

bool SetLineColor ( int Col , int Color = 36);

// деструктор
virtual ~ExcelCom();
};

#endif // !defined(AFX_EXCELCOM_H__E1613E65_0F18_454E_B424_64476E091C7C__INCLUDED_)

// ExcelCom.cpp: implementation of the ExcelCom class.
//
//////////////////////////////////////////////////////////////////////

#include "stdafx.h"
#include "ExcelCom.h"

#ifdef _DEBUG
#undef THIS_FILE
static char THIS_FILE[]=__FILE__;
#define new DEBUG_NEW
#endif

#include <DBMoney.h>

//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////

ExcelCom::ExcelCom() : m_Valid(false)
{
}

ExcelCom::~ExcelCom()
{
Release();
CoUninitialize();
}

bool ExcelCom::Init()
{
HRESULT hr = ::CoInitialize(NULL);

if(SUCCEEDED(hr) )
{
CLSID id;
CLSIDFromProgID(L"Excel.Application", &id);
IDispatch* pDisp;
hr=::CoCreateInstance(id,NULL,CLSCTX_LOCAL_SERVER,IID_IDispatch,(void**)&pDisp);

if( SUCCEEDED(hr) )
{
this->p = pDisp;

CComVariant res;
hr = GetPropertyByName(L"Workbooks",&res);
if (res.pdispVal)
{
CComDispatchDriver wbDisp(res.pdispVal);
hr=wbDisp.Invoke0(L"Add");

m_Valid = true;
}
}
}

if(m_Valid) Minimiz();

return m_Valid;
}

// разделение имени на чистое_имя и параметр VARIANT
bool ExcelCom::GetPureName(CString Name, CString &PureName, VARIANT &arg)
{
CString Val;

if(Name.Find('(') != -1)
{
PureName = Name.Mid(0,Name.Find('('));
Val = Name.Mid(Name.Find('(')+1);
Val = Val.Mid(0,Val.Find(')'));

Val.TrimRight();
Val.TrimLeft();

// определение типа параметра
if(Val.Left(1) == "/"" && Val.Right(1) == "/"")
{
// строковый
Val.Replace("/"","");
arg.vt = VT_BSTR;
arg.bstrVal = SysAllocString(Val.AllocSysString());
}
else if(Val == "True" || Val == "False")
{
// логический
arg.vt = VT_BOOL;
if(Val.Find("True") != -1) arg.boolVal = TRUE;
if(Val.Find("False") != -1) arg.boolVal = FALSE;
}
else if(Val.Left(2) == "xl")
{
// константа xl
arg.vt = VT_I4;
arg.lVal = xlConst(Val);
}
else // целочисленный //Arg.vt = VT_I2; Arg.iVal = atoi(ArgStr);
{
arg.vt = VT_I4;
arg.lVal = atol(Val);
}
}
else
{
PureName = Name; PureName.TrimRight(); PureName.TrimLeft();
return false;
}

PureName.TrimRight(); PureName.TrimLeft();
return true;
}

// получить свойство [например Range("D13") или Sheets(1) ]
CComVariant ExcelCom::GetProp(IDispatch* p, CString Name)
{
// выделяем чистое имя и параметр
VARIANT arg;
CString PureName;

bool bArg = GetPureName(Name, PureName, arg);

HRESULT hr;
CComVariant res;
CComDispatchDriver wbDisp(p);

if(bArg)
{
DISPID dwDispIDRange;

hr = GetIDOfName(PureName.AllocSysString(), &dwDispIDRange);
if (FAILED(hr)) return false;

DISPPARAMS dispparms;
VARIANT vArgs[1];

memset(vArgs, 0, sizeof(VARIANT) * 1);

vArgs[0] = arg;
dispparms.cArgs = 1;
dispparms.rgvarg = vArgs;
dispparms.cNamedArgs = 0;

hr = wbDisp->Invoke(dwDispIDRange, IID_NULL, LOCALE_USER_DEFAULT,
DISPATCH_PROPERTYGET, &dispparms, &res, NULL, NULL);

if (FAILED(hr)) return false;
}
else
{
hr = wbDisp.GetPropertyByName(PureName.AllocSysString(),&res);
if (FAILED(hr)) return false;
}

return res;
}

// присвоение значения выбранному свойству
bool ExcelCom::SetProp(IDispatch* p, CString PropName, CString Val)
{
VARIANT arg;
CString PureName;

bool bArg = GetPureName(PropName+"("+Val+")", PureName, arg);

HRESULT hr;
CComDispatchDriver wbDisp(p);
hr = wbDisp.PutPropertyByName(PureName.AllocSysString(),&arg);

if (FAILED(hr)) return false;
return true;
}

// вызов метода с параметрами
bool ExcelCom::RunFunc(IDispatch* p, CString Name)
{
CString PureName;
VARIANT arg, res;

bool bArg = GetPureName(Name, PureName, arg);

HRESULT hr;
CComDispatchDriver wbDisp(p);

if(bArg) { hr = wbDisp.Invoke1(PureName.AllocSysString(),&arg,&res); }
else { hr = wbDisp.Invoke0(PureName.AllocSysString(),&res); }

if (FAILED(hr)) return false;
return true;
}
// выполнить несколько команд
bool ExcelCom::ExecVbaSrc(CString VbSrc, int aRow)
{
int Pos = 0;
CString cmd = "";

if(aRow)
{
// это код форматирования строки
// проводим замену формулы вида RC[1] на ячейку
while( (Pos = VbSrc.Find("RC[")) != -1 && VbSrc.Find(']') != -1)
{
cmd = CString(cmd) + VbSrc.Mid(0,Pos);
VbSrc = VbSrc.Mid(Pos+3);
int aCol = atol( VbSrc.Mid( 0 , VbSrc.Find(']') ) );
cmd = CString(cmd) + sCell(aRow,aCol);
VbSrc = VbSrc.Mid(VbSrc.Find(']')+1);
}
cmd = CString(cmd) + VbSrc;
}
else cmd = VbSrc;

// команды через /n
CString line = "";
while( (Pos = cmd.Find("/r/n")) != -1 )
{
line = cmd.Mid(0,Pos);
cmd = cmd.Mid(Pos+1);

line.TrimLeft();
line.TrimRight();

if(line.GetLength() && line[0]!='/'')
{
if(ExecBasLine(line)) continue;
else return false;
}
}
cmd.TrimLeft();
cmd.TrimRight();

if(cmd.GetLength() && cmd[0]!='/'')
{
if(ExecBasLine(cmd)) return true;
else return false;
}
return true;
}

// выполнить команду на басике
bool ExcelCom::ExecBasLine(CString cmd)
{
cmd.OemToAnsi();
std::vector<CString> vNames;
CString Val;

// возможные команды
if(cmd.Find('=') != -1)
{
// команда присвоениия свойству некоторого значения
Val = cmd.Mid(cmd.Find('=')+1);
cmd = cmd.Mid(0,cmd.Find('='));
}

// заполняем массив vNames
while(cmd.Find('.') != -1)
{
CString Name = cmd.Mid(0,cmd.Find('.'));
cmd = cmd.Mid(cmd.Find('.')+1);
vNames.push_back(Name);
}

// получаем нужный объект
CComVariant res(this->CComDispatchDriver::p);

for(int i=0;i<vNames.size();i++)
{
if(res.pdispVal) res = GetProp(res.pdispVal , vNames[i]);
else return false;
}

if(!res.pdispVal) return false;

bool bResult;
// выполняем команду или присваивание значения
if(Val.GetLength() != 0) bResult = SetProp( res.pdispVal, cmd , Val);
else bResult = RunFunc( res.pdispVal, cmd);

return bResult;
}

// выполнить команду на басике (получает значение)
bool ExcelCom::ExecBasLine(VARIANT &value, CString cmd)
{
// просто берём указанное свойство и пишим в Value
cmd.OemToAnsi();

std::vector<CString> vNames;

// команда получает значение выражения
if(cmd.Find('=') != -1) cmd = cmd.Mid(cmd.Find('=')+1);
else return false;

// заполняем массив vNames
while(cmd.Find('.') != -1)
{
CString Name = cmd.Mid(0,cmd.Find('.'));
cmd = cmd.Mid(cmd.Find('.')+1);
vNames.push_back(Name);
}
vNames.push_back(cmd);

// получаем нужный объект
CComVariant res(this->CComDispatchDriver::p);

for(int i=0;i<vNames.size();i++)
{
if(res.pdispVal) res = GetProp(res.pdispVal , vNames[i]);
else return false;
}

value = res;
return true;
}

bool ExcelCom::Restore()
{
SetVisible();
return WindowState(xlNormal);
}

void ExcelCom::SetVisible(bool bVisible)
{
CComVariant arg1(bVisible);
PutPropertyByName(L"Visible",&arg1);
}

bool ExcelCom::OpenFile(CString FName)
{
CComVariant res,arg1;
HRESULT hr = GetPropertyByName(L"Workbooks",&res);

if (res.pdispVal)
{
arg1 = FName;
CComDispatchDriver wbDisp(res.pdispVal);
hr = wbDisp.Invoke1(L"Open",&arg1,&res);

return true;
}
return false;
}

bool ExcelCom::SaveFileAs(CString FName)
{
// сохранение файла
CComVariant res,arg1;
HRESULT hr = GetPropertyByName(L"ActiveWorkbook",&res);

if (res.pdispVal)
{
arg1 = FName;
CComDispatchDriver wbDisp(res.pdispVal);
hr = wbDisp.Invoke1(L"SaveAs",&arg1,&res);

return true;
}
return false;
}

bool ExcelCom::CloseAllBooks()
{
// сохранение файла
CComVariant res,arg1;
HRESULT hr = GetPropertyByName(L"Workbooks",&res);

if (res.pdispVal)
{
CComDispatchDriver wbDisp(res.pdispVal);
hr = wbDisp.Invoke0(L"Close",&res);

return true;
}
return false;
}

bool ExcelCom::WindowState(XlWindowState ws)
{
CComVariant arg1(ws, VT_I4);
PutPropertyByName(L"WindowState",&arg1);
return true;
}

bool ExcelCom::Close()
{
Invoke0(L"Quit");
return true;
}

bool ExcelCom::PutRange(int aRow, int aCol, CComVariant arg1)
{
HRESULT hr;
DISPID dwDispIDRange;

hr = GetIDOfName(L"Range", &dwDispIDRange);
if (FAILED(hr)) return false;

DISPPARAMS dispparms;
VARIANT vResult,vArgs[1];

memset(vArgs, 0, sizeof(VARIANT) * 1);

vArgs[0] = vCell(aRow,aCol);

dispparms.cArgs = 1;
dispparms.rgvarg = vArgs;
dispparms.cNamedArgs = 0;

hr = (*this)->Invoke(dwDispIDRange, IID_NULL, LOCALE_USER_DEFAULT,
DISPATCH_PROPERTYGET, &dispparms, &vResult, NULL, NULL);
if (FAILED(hr)) return false;

CComDispatchDriver spRange(vResult.pdispVal);

hr = spRange.PutPropertyByName(L"FormulaR1C1",&arg1);
if (FAILED(hr)) return false;

return true;
}

bool ExcelCom::PutStr(int aRow, int aCol, const char *aStr)
{
CString buf(aStr);

buf.OemToAnsi();

// CComVariant arg1(aStr);
CComVariant arg1(static_cast<const char*>("/'"+buf));
return(PutRange(aRow, aCol, arg1));

}

CString ExcelCom::sCell(int aRow, int aCol)
{
CString cell;
const char abc[28] = " ABCDEFGHIJKLMNOPQRSTUVWXYZ"; // 26

int n1 = (aCol-1)/26;
int n2 = aCol%26 ? aCol%26 : 26;

cell.Format("%c%c%d",abc[n1],abc[n2],aRow);
cell.TrimLeft();
return cell;
}

VARIANT ExcelCom::vCell(int aRow, int aCol)
{
CString cell = sCell(aRow,aCol);
VARIANT res;
res.vt = VT_BSTR;
res.bstrVal = SysAllocString(cell.AllocSysString());
return res;
}

bool ExcelCom::PutDoub(int aRow, int aCol, double aArg, int prec)
{
CComVariant arg1((double)DBMoney(aArg).Round(-prec));
return(PutRange(aRow, aCol, arg1));
}

bool ExcelCom::PutDate(int aRow, int aCol, DBTime aArg)
{
CComVariant arg1;
arg1.vt = VT_DATE;
arg1.date = aArg;
return(PutRange(aRow, aCol, arg1));
}

bool ExcelCom::PutInt(int aRow, int aCol, long aArg)
{
CComVariant arg1(aArg);
return(PutRange(aRow, aCol, arg1));

}

// интерфейс для работы с листами Exceell
bool ExcelCom::AddNewList()
{
return ExecBasLine("ActiveWorkbook.Sheets.Add");
}

CString ExcelCom::GetListName()
{
CComVariant val;
ExecBasLine(val," = ActiveWindow.ActiveSheet.Name");

if(val.vt == VT_BSTR)
{
CString res(val.bstrVal);
res.AnsiToOem();
return res;
}
return "";
}

int ExcelCom::GetListCount()
{
CComVariant val;
ExecBasLine(val," = ActiveWorkbook.Sheets.Count");

if(val.vt == VT_I4) return val.lVal;
if(val.vt == VT_I2) return val.iVal;

return -1;
}

bool ExcelCom::DeleteList(CString ListName)
{
return ExecBasLine("ActiveWorkbook.Sheets(/""+ ListName + "/").Delete");
}

bool ExcelCom::RenameList(CString ListName)
{
return ExecBasLine("ActiveWindow.ActiveSheet.Name = /"" + ListName + "/"");
}

bool ExcelCom::DeleteList(int ListNum)
{
CString cmd;
cmd.Format("ActiveWorkbook.Sheets(%i).Delete",ListNum);
return ExecBasLine(cmd);
}

bool ExcelCom::SelectList(int ListNum)
{
CString cmd;
cmd.Format("ActiveWorkbook.Sheets(%i).Select",ListNum);
return ExecBasLine(cmd);
}

bool ExcelCom::SelectList(CString ListName)
{
return ExecBasLine("ActiveWorkbook.Sheets(/"" + ListName + "/").Select");
}

bool ExcelCom::SetColumeWidth( int Col , int Width)
{
CString cmd;
cmd.Format("Columns(%i).ColumnWidth = %i", Col , Width);
return ExecBasLine(cmd);
}

bool ExcelCom::SetBold(int Row, int Col)
{
CString cmd;
cmd.Format("Range(/"%s/").Select",sCell(Row,Col));
if(ExecBasLine(cmd)) return ExecBasLine("Selection.Font.Bold = True");
return false;
}

bool ExcelCom::SetBoldLine( int Row)
{
CString cmd;
cmd.Format("Rows(%i).Select", Row);
if(ExecBasLine(cmd)) return ExecBasLine("Selection.Font.Bold = True");
return false;
}

bool ExcelCom::SetBoldColum( int Col)
{
CString cmd;
cmd.Format("Columns(%i).Select", Col);
if(ExecBasLine(cmd)) return ExecBasLine("Selection.Font.Bold = True");
return false;
}

bool ExcelCom::SetItalic(int Row, int Col)
{
CString cmd;
cmd.Format("Range(/"%s/").Select",sCell(Row,Col));
if(ExecBasLine(cmd)) return ExecBasLine("Selection.Font.Italic = True");
return false;
}

bool ExcelCom::SetItalicLine( int Row)
{
CString cmd;
cmd.Format("Rows(%i).Select", Row);
if(ExecBasLine(cmd)) return ExecBasLine("Selection.Font.Italic = True");
return false;
}

bool ExcelCom::SetItalicColum( int Col)
{
CString cmd;
cmd.Format("Columns(%i).Select", Col);
if(ExecBasLine(cmd)) return ExecBasLine("Selection.Font.Italic = True");
return false;
}

bool ExcelCom::SetLineColor( int Col, int Color)
{
CString cmd1, cmd2;
cmd1.Format("Rows(%i).Select", Col);
cmd2.Format("Selection.Interior.ColorIndex = %i", Color);

if(ExecBasLine(cmd1)) return ExecBasLine(cmd2);
return false;
}

bool ExcelCom::PutFormula(int aRow, int aCol, CString aFml)
{
// закидываем в Excell формулу вида
// =SUM([#+2,_-5]:[#-1,_+2]) # - столбец _ - строка
/*
CString res = "", val = "";
while(aFml.Find('[') != -1 && aFml.Find(']') != -1)
{
res = CString(res) + aFml.Mid(0,aFml.Find('['));
aFml = aFml.Mid(aFml.Find('[')+1);
val = aFml.Mid(0,aFml.Find(']'));
aFml = aFml.Mid(aFml.Find(']')+1);

// преобразование val в значение ячейки и добавление к res
val.Replace("#",""); val.Replace("_","");

CString sCol = val.Mid(0,val.Find(','));
CString sRow = val.Mid(val.Find(',')+1);
res = CString(res) + sCell( aRow + atol(sRow), aCol + atol(sCol));
}

res = CString(res) + aFml;

CString cmd1,cmd2;
cmd1.Format("Range(/"%s/").Select",sCell(aRow,aCol));
cmd2.Format("ActiveCell.Formula = /"%s/"",res);

if(ExecBasLine(cmd1)) return ExecBasLine(cmd2);
return false;
*/

aFml.OemToAnsi();
CComVariant arg1(aFml);
return(PutRange(aRow, aCol, arg1));
}

int ExcelCom::xlConst(CString xl)
{
if( xl == "xlMaximized") return xlMaximized ;
if( xl == "xlMinimized") return xlMinimized ;
if( xl == "xlNormal") return xlNormal ;
if( xl == "xlInsideHorizontal") return xlInsideHorizontal ;
if( xl == "xlInsideVertical") return xlInsideVertical ;
if( xl == "xlDiagonalDown") return xlDiagonalDown ;
if( xl == "xlDiagonalUp") return xlDiagonalUp ;
if( xl == "xlEdgeBottom") return xlEdgeBottom ;
if( xl == "xlEdgeLeft") return xlEdgeLeft ;
if( xl == "xlEdgeRight") return xlEdgeRight ;
if( xl == "xlEdgeTop") return xlEdgeTop ;
if( xl == "xlContinuous") return xlContinuous ;
if( xl == "xlDash") return xlDash ;
if( xl == "xlDashDot") return xlDashDot ;
if( xl == "xlDashDotDot") return xlDashDotDot ;
if( xl == "xlDot") return xlDot ;
if( xl == "xlDouble") return xlDouble ;
if( xl == "xlSlantDashDot") return xlSlantDashDot ;
if( xl == "xlLineStyleNone") return xlLineStyleNone ;
if( xl == "xlHairline") return xlHairline ;
if( xl == "xlMedium") return xlMedium ;
if( xl == "xlThick") return xlThick ;
if( xl == "xlThin") return xlThin ;
if( xl == "xlAll") return xlAll ;
if( xl == "xlAutomatic") return xlAutomatic ;
if( xl == "xlBoth") return xlBoth ;
if( xl == "xlCenter") return xlCenter ;
if( xl == "xlChecker") return xlChecker ;
if( xl == "xlCircle") return xlCircle ;
if( xl == "xlCorner") return xlCorner ;
if( xl == "xlCrissCross") return xlCrissCross ;
if( xl == "xlCross") return xlCross ;
if( xl == "xlDiamond") return xlDiamond ;
if( xl == "xlDistributed") return xlDistributed ;
if( xl == "xlDoubleAccounting") return xlDoubleAccounting ;
if( xl == "xlFixedValue") return xlFixedValue ;
if( xl == "xlFormats") return xlFormats ;
if( xl == "xlGray16 ") return xlGray16 ;
if( xl == "xlGray8 ") return xlGray8 ;
if( xl == "xlGrid ") return xlGrid ;
if( xl == "xlHigh ") return xlHigh ;
if( xl == "xlInside ") return xlInside ;
if( xl == "xlJustify ") return xlJustify ;
if( xl == "xlLightDown ") return xlLightDown ;
if( xl == "xlLightHorizontal ") return xlLightHorizontal ;
if( xl == "xlLightUp ") return xlLightUp ;
if( xl == "xlLightVertical") return xlLightVertical ;
if( xl == "xlLow ") return xlLow ;
if( xl == "xlManual ") return xlManual ;
if( xl == "xlMinusValues") return xlMinusValues ;
if( xl == "xlModule") return xlModule ;
if( xl == "xlNextToAxis") return xlNextToAxis ;
if( xl == "xlNone") return xlNone ;
if( xl == "xlNotes") return xlNotes ;
if( xl == "xlOff") return xlOff ;
if( xl == "xlOn") return xlOn ;
if( xl == "xlPercent") return xlPercent ;
if( xl == "xlPlus") return xlPlus ;
if( xl == "xlPlusValues") return xlPlusValues ;
if( xl == "xlSemiGray75") return xlSemiGray75 ;
if( xl == "xlShowLabel") return xlShowLabel ;
if( xl == "xlShowLabelAndPercent") return xlShowLabelAndPercent ;
if( xl == "xlShowPercent") return xlShowPercent ;
if( xl == "xlShowValue") return xlShowValue ;
if( xl == "xlSimple") return xlSimple ;
if( xl == "xlSingle") return xlSingle ;
if( xl == "xlSingleAccounting") return xlSingleAccounting ;
if( xl == "xlSolid") return xlSolid ;
if( xl == "xlSquare") return xlSquare ;
if( xl == "xlStar") return xlStar ;
if( xl == "xlStError") return xlStError ;
if( xl == "xlToolbarButton") return xlToolbarButton ;
if( xl == "xlTriangle") return xlTriangle ;
if( xl == "xlGray25") return xlGray25 ;
if( xl == "xlGray50") return xlGray50 ;
if( xl == "xlGray75") return xlGray75 ;
if( xl == "xlBottom") return xlBottom ;
if( xl == "xlLeft") return xlLeft ;
if( xl == "xlRight") return xlRight ;
if( xl == "xlTop") return xlTop ;
if( xl == "xl3DBar") return xl3DBar ;
if( xl == "xl3DSurface") return xl3DSurface ;
if( xl == "xlBar") return xlBar ;
if( xl == "xlColumn") return xlColumn ;
if( xl == "xlCombination") return xlCombination ;
if( xl == "xlCustom") return xlCustom ;
if( xl == "xlDefaultAutoFormat") return xlDefaultAutoFormat ;
if( xl == "xlMaximum") return xlMaximum ;
if( xl == "xlMinimum") return xlMinimum ;
if( xl == "xlOpaque") return xlOpaque ;
if( xl == "xlTransparent") return xlTransparent ;
if( xl == "xlBidi") return xlBidi ;
if( xl == "xlLatin") return xlLatin ;
if( xl == "xlContext") return xlContext ;
if( xl == "xlLTR") return xlLTR ;
if( xl == "xlRTL") return xlRTL ;
if( xl == "xlFullScript") return xlFullScript ;
if( xl == "xlPartialScript") return xlPartialScript ;
if( xl == "xlMixedScript") return xlMixedScript ;
if( xl == "xlMixedAuthorizedScript")return xlMixedAuthorizedScript ;
if( xl == "xlVisualCursor") return xlVisualCursor ;
if( xl == "xlLogicalCursor") return xlLogicalCursor ;
if( xl == "xlSystem") return xlSystem ;
if( xl == "xlPartial") return xlPartial ;
if( xl == "xlHindiNumerals") return xlHindiNumerals ;
if( xl == "xlBidiCalendar") return xlBidiCalendar ;
if( xl == "xlGregorian") return xlGregorian ;
if( xl == "xlComplete") return xlComplete ;
if( xl == "xlScale") return xlScale ;
if( xl == "xlClosed") return xlClosed ;
if( xl == "xlColor1") return xlColor1 ;
if( xl == "xlColor2") return xlColor2 ;
if( xl == "xlColor3") return xlColor3 ;
if( xl == "xlConstants") return xlConstants ;
if( xl == "xlContents") return xlContents ;
if( xl == "xlBelow") return xlBelow ;
if( xl == "xlCascade") return xlCascade ;
if( xl == "xlCenterAcrossSelection")return xlCenterAcrossSelection ;
if( xl == "xlChart4") return xlChart4 ;
if( xl == "xlChartSeries") return xlChartSeries ;
if( xl == "xlChartShort") return xlChartShort ;
if( xl == "xlChartTitles") return xlChartTitles ;
if( xl == "xlClassic1") return xlClassic1 ;
if( xl == "xlClassic2") return xlClassic2 ;
if( xl == "xlClassic3") return xlClassic3 ;
if( xl == "xl3DEffects1") return xl3DEffects1 ;
if( xl == "xl3DEffects2") return xl3DEffects2 ;
if( xl == "xlAbove") return xlAbove ;
if( xl == "xlAccounting1") return xlAccounting1 ;
if( xl == "xlAccounting2") return xlAccounting2 ;
if( xl == "xlAccounting3") return xlAccounting3 ;
if( xl == "xlAccounting4") return xlAccounting4 ;
if( xl == "xlAdd") return xlAdd ;
if( xl == "xlDebugCodePane") return xlDebugCodePane ;
if( xl == "xlDesktop") return xlDesktop ;
if( xl == "xlDirect") return xlDirect ;
if( xl == "xlDivide") return xlDivide ;
if( xl == "xlDoubleClosed") return xlDoubleClosed ;
if( xl == "xlDoubleOpen") return xlDoubleOpen ;
if( xl == "xlDoubleQuote") return xlDoubleQuote ;
if( xl == "xlEntireChart") return xlEntireChart ;
if( xl == "xlExcelMenus") return xlExcelMenus ;
if( xl == "xlExtended") return xlExtended ;
if( xl == "xlFill") return xlFill ;
if( xl == "xlFirst") return xlFirst ;
if( xl == "xlFloating") return xlFloating ;
if( xl == "xlFormula") return xlFormula ;
if( xl == "xlGeneral") return xlGeneral ;
if( xl == "xlGridline") return xlGridline ;
if( xl == "xlIcons") return xlIcons ;
if( xl == "xlImmediatePane") return xlImmediatePane ;
if( xl == "xlInteger") return xlInteger ;
if( xl == "xlLast") return xlLast ;
if( xl == "xlLastCell") return xlLastCell ;
if( xl == "xlList1") return xlList1 ;
if( xl == "xlList2") return xlList2 ;
if( xl == "xlList3") return xlList3 ;
if( xl == "xlLocalFormat1") return xlLocalFormat1 ;
if( xl == "xlLocalFormat2") return xlLocalFormat2 ;
if( xl == "xlLong") return xlLong ;
if( xl == "xlLotusHelp") return xlLotusHelp ;
if( xl == "xlMacrosheetCell") return xlMacrosheetCell ;
if( xl == "xlMixed") return xlMixed ;
if( xl == "xlMultiply") return xlMultiply ;
if( xl == "xlNarrow") return xlNarrow ;
if( xl == "xlNoDocuments") return xlNoDocuments ;
if( xl == "xlOpen") return xlOpen ;
if( xl == "xlOutside") return xlOutside ;
if( xl == "xlReference") return xlReference ;
if( xl == "xlSemiautomatic") return xlSemiautomatic ;
if( xl == "xlShort") return xlShort ;
if( xl == "xlSingleQuote") return xlSingleQuote ;
if( xl == "xlStrict") return xlStrict ;
if( xl == "xlSubtract") return xlSubtract ;
if( xl == "xlTextBox") return xlTextBox ;
if( xl == "xlTiled") return xlTiled ;
if( xl == "xlTitleBar") return xlTitleBar ;
if( xl == "xlToolbar") return xlToolbar ;
if( xl == "xlVisible") return xlVisible ;
if( xl == "xlWatchPane") return xlWatchPane ;
if( xl == "xlWide") return xlWide ;
if( xl == "xlWorkbookTab") return xlWorkbookTab ;
if( xl == "xlWorksheet4") return xlWorksheet4 ;
if( xl == "xlWorksheetCell") return xlWorksheetCell ;
if( xl == "xlWorksheetShort") return xlWorksheetShort ;
if( xl == "xlAllExceptBorders") return xlAllExceptBorders ;
if( xl == "xlLeftToRight") return xlLeftToRight ;
if( xl == "xlTopToBottom") return xlTopToBottom ;
if( xl == "xlVeryHidden") return xlVeryHidden ;
if( xl == "xlDrawingObject") return xlDrawingObject ;

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: