要使用`COleSafeArray`將字符串寫入Excel中,您需要遵循以下步驟:
1. 引入必要的頭文件:
#include#include
2. 創(chuàng)建一個(gè)`COleVariant`對(duì)象來存儲(chǔ)要寫入的字符串值:
CString strValue = "Hello, World!"; COleVariant var(strValue);
3. 將`COleVariant`對(duì)象轉(zhuǎn)換為`COleSafeArray`對(duì)象:
COleSafeArray sa; sa.CreateOneDim(VT_VARIANT, 1); LONG index[] = {0}; sa.PutElement(index, &var);
4. 打開Excel應(yīng)用程序并獲取`IDispatch`接口指針:
_Application app; app.CreateDispatch("Excel.Application");
5. 打開或創(chuàng)建一個(gè)工作簿:
Workbooks workbooks = app.GetWorkbooks(); _Workbook workbook; workbooks.Open(L"C:\\path\\to\\Workbook.xlsx", NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL); // 如果要?jiǎng)?chuàng)建新的工作簿,請(qǐng)使用下面的代碼: // _Workbook workbook = workbooks.Add();
6. 獲取工作表對(duì)象:
Sheets sheets = workbook.GetSheets(); _Worksheet sheet; sheet = sheets.GetItem(COleVariant((short)(1)));
7. 將字符串值寫入單元格:
Range range; range = sheet.GetCells(); range = range.GetItem(COleVariant((long)(1)), COleVariant((long)(1))); range.SetValue(COleVariant(sa));
8. 保存并關(guān)閉工作簿:
workbook.Save(); workbook.Close();
9. 退出Excel應(yīng)用程序:
app.Quit();
完整的示例代碼如下:
#include#include int main() { CoInitialize(NULL); CString strValue = "Hello, World!"; COleVariant var(strValue); COleSafeArray sa; sa.CreateOneDim(VT_VARIANT, 1); LONG index[] = {0}; sa.PutElement(index, &var); _Application app; app.CreateDispatch("Excel.Application"); Workbooks workbooks = app.GetWorkbooks(); _Workbook workbook; workbooks.Open(L"C:\\path\\to\\Workbook.xlsx", NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL); //_Workbook workbook = workbooks.Add(); Sheets sheets = workbook.GetSheets(); _Worksheet sheet; sheet = sheets.GetItem(COleVariant((short)(1))); Range range; range = sheet.GetCells(); range = range.GetItem(COleVariant((long)(1)), COleVariant((long)(1))); range.SetValue(COleVariant(sa)); workbook.Save(); workbook.Close(); app.Quit(); CoUninitialize(); return 0; }
請(qǐng)確保已經(jīng)鏈接到`ole32.lib`和`afxdisp.lib`庫(kù),并將文件路徑替換為實(shí)際的Excel工作簿路徑。