需求:字串格式 {小明|25|2011070737|}{小紅|24|2011070764},依 `|` 分隔欄位,依 `}{` 分隔列,插入 MFC CListCtrl (報表模式),欄位標題為 `姓名|年齡|學號`。
void InsertDataToListCtrl(CListCtrl& list, const CString& strData) {
// 1. 設定欄位 (僅第一次呼叫需執行)
static bool bColumnInited = false;
if (!bColumnInited) {
list.InsertColumn(0, _T("姓名"), LVCFMT_LEFT, 100);
list.InsertColumn(1, _T("年齡"), LVCFMT_CENTER, 80);
list.InsertColumn(2, _T("學號"), LVCFMT_LEFT, 120);
bColumnInited = true;
}
// 2. 解析資料列:以 "}{" 分隔
CString str = strData;
str.TrimLeft(_T("{")); // 移除首 {
str.TrimRight(_T("}")); // 移除尾 }
int row = 0;
int pos = 0;
CString token = str.Tokenize(_T("}{"), pos); // Tokenize 會修改字串,建議複製
while (!token.IsEmpty()) {
// 3. 解析欄位:以 "|" 分隔
int col = 0;
int colPos = 0;
CString field = token.Tokenize(_T("|"), colPos);
int nItem = list.InsertItem(row, _T("")); // 插入新行
while (!field.IsEmpty() && col < 3) {
list.SetItemText(nItem, col, field);
field = token.Tokenize(_T("|"), colPos);
col++;
}
row++;
token = str.Tokenize(_T("}{"), pos);
}
}
| 操作 | MFC 方法 | 說明 |
|---|---|---|
| 插入欄位 | InsertColumn(nCol, heading, fmt, width) | 報表模式必須先插入欄位 |
| 插入列 | InsertItem(nItem, label) | 返回實際插入索引,第 0 欄文字 |
| 設定單元格 | SetItemText(nItem, nSubItem, text) | 第 1 欄起用 nSubItem=1,2... |
| 字串分割 | CString::Tokenize(pszTokens, startPos) | 支援多字元分隔符,需注意修改原字串 |
CStringArray rows;
SplitString(strData, _T("}{"), rows); // 自寫 Split 函式或用 CAtlArray
for (int r = 0; r < rows.GetCount(); r++) {
CStringArray cols;
SplitString(rows[r], _T("|"), cols);
int nItem = list.InsertItem(r, cols[0]);
list.SetItemText(nItem, 1, cols[1]);
list.SetItemText(nItem, 2, cols[2]);
}
Tokenize 會修改原字串 → 傳入副本 CString str = strData;。}{` 包含特殊字元,`Tokenize` 視為字元集合而非字串 → 需自寫 Find 迴圈分割。SetRedraw(FALSE),完成後 SetRedraw(TRUE); Invalidate() 防止閃爍。
void SplitString(const CString& src, const CString& delim, CStringArray& out) {
int start = 0;
while (true) {
int pos = src.Find(delim, start);
if (pos == -1) {
out.Add(src.Mid(start));
break;
}
out.Add(src.Mid(start, pos - start));
start = pos + delim.GetLength();
}
}
掌握 CListCtrl 報表模式基本操作與字串分割技巧,即可靈活處理各類格式化資料導入需求。