要使用`COleSafeArray`將字符串寫入Excel中,您需要遵循以下步驟:
1. 引入必要的頭文件:
#include#include
2. 創建一個`COleVariant`對象來存儲要寫入的字符串值:
CString strValue = "Hello, World!"; COleVariant var(strValue);
3. 將`COleVariant`對象轉換為`COleSafeArray`對象:
COleSafeArray sa; sa.CreateOneDim(VT_VARIANT, 1); LONG index[] = {0}; sa.PutElement(index, &var);
4. 打開Excel應用程序并獲取`IDispatch`接口指針:
_Application app; app.CreateDispatch("Excel.Application");
5. 打開或創建一個工作簿:
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();
6. 獲取工作表對象:
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. 保存并關閉工作簿:
workbook.Save(); workbook.Close();
9. 退出Excel應用程序:
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; }
請確保已經鏈接到`ole32.lib`和`afxdisp.lib`庫,并將文件路徑替換為實際的Excel工作簿路徑。