EXCEL2016 OLE/COM開發-常用功能封裝代碼


 

hpp

  1 #pragma once
  2 #include "stdafx.h"
  3 #include "CApplication.h"
  4 #include "CWorkbook.h"
  5 #include "CWorksheet.h"
  6 #include "CRange.h"
  7 #include "CWorkbooks.h"
  8 #include "CWorksheets.h"
  9 #include "Cnterior.h"
 10 #include "CFont0.h"
 11 #include "CShape.h"
 12 #include "CShapes.h"
 13 #include <string>
 14 #include <vector>
 15 
 16 using namespace std;
 17 
 18 class ExcelApi
 19 {
 20 public:
 21     ExcelApi(void);
 22     ~ExcelApi(void);
 23 
 24     // 初始化Excel OLE
 25     BOOL InitExcel();
 26 
 27     /**
 28     * @brief 新建Excel
 29     * @param[in] ExcalPath  路徑
 30     */
 31     void CreateExcel(const char* ExcalPath);
 32 
 33     /**
 34     * @brief 打開Excel
 35     * @param[in] filePath  路徑
 36     * @param[in] type  打開時是否顯示EXCEL
 37     * @return BOOL 打開成功&失敗
 38     */
 39     BOOL OpenFile(const char* filePath, bool type);
 40 
 41 
 42     /**
 43     * @brief 關閉Excel
 44     */
 45     void CloseExcel();
 46 
 47 
 48     /**
 49     * @brief 保存Excel
 50     */
 51     void Save();
 52 
 53 
 54     /**
 55     * @brief 獲取所有的工作表數量
 56     * @return int 數量
 57     */
 58     int GetSheetCount();
 59 
 60 
 61     /**
 62     * @brief 設置當前工作表
 63     * @param[in] id  第幾個sheet,從1開始
 64     * @return BOOL 設置成功&失敗
 65     */
 66     BOOL SetCurrentSheetByNum(const int& id);
 67 
 68 
 69     /**
 70     * @brief 設置當前工作表
 71     * @param[in] sheet_name  sheet的名字
 72     * @return BOOL 設置成功&失敗
 73     */
 74     BOOL SetCurrentSheetByName(string sheet_name);
 75 
 76 
 77     /**
 78     * @brief 獲取單元格數據
 79     * @param[in] row  行
 80     * @param[in] column  列
 81     * @return string 內容
 82     */
 83     string GetRangeData(const int row, const int column);
 84 
 85 
 86     /**
 87     * @brief 獲取sheet名字
 88     * @return string 名字
 89     */
 90     string GetSheetName();
 91 
 92 
 93     /**
 94     * @brief 設置sheet名字
 95     */
 96     void SetSheetName(const int SheetNum, const char* SheetName);
 97 
 98 
 99     /**
100     * @brief 當前sheet單元格寫入內容
101     * @param[in] row  行
102     * @param[in] column  列
103     * @param[in] Data  內容
104     */
105     void SetRangeData(const int row, const int column, const char* Data);
106 
107 
108     /**
109     * @brief 獲得當前sheet使用的行數
110     * @return int 數量
111     */
112     int GetRowNum();
113 
114 
115     /**
116     * @brief 獲得當前sheet使用的列數
117     * @return int 數量
118     */
119     int GetColumnNum();
120 
121 
122     /**
123     * @brief 刪除單元格
124     * @param[in] A1  起始單元格
125     * @param[in] B1  結束單元格
126     * @param[in] type  類型(設置刪除類型1.右側單元格左移 2.下方單元格上移 3.整行 4.整列)
127     */
128     void DeleteRange(char* A1, char* B1, int type);
129 
130     /**
131     * @brief 添加單元格
132     * @param[in] A1  起始單元格
133     * @param[in] B1  結束單元格
134     * @param[in] type  類型(設置添加類型1.右側單元格左移 2.下方單元格上移 3.整行 4.整列)
135     */
136     void AddRange(char* A1, char* B1, int type);
137 
138 
139     /**
140     * @brief 設置字體和顏色
141     * @param[in] A1  起始單元格
142     * @param[in] B1  結束單元格
143     * @param[in] FontType  字體類型
144     * @param[in] FontColor  字體顏色
145     * @param[in] FontSize  字體大小
146     */
147     void SetFont(char* A1, char* B1, char* FontType, int FontColor, int FontSize);
148 
149 
150     /**
151     * @brief 設置單元格填充顏色
152     * @param[in] A1  起始單元格
153     * @param[in] B1  結束單元格
154     * @param[in] FontColor  顏色
155     */
156     void SetRangeColor(char* A1, char* B1, int RangeColor);
157 
158 
159     /**
160     * @brief 遍歷某一單元格,替換內容
161     * @param[in] CycleName  要遍歷的名字
162     * @param[in] NewName  寫入的新名字
163     */
164     void CycleRangeSetData(char* CycleName, char* NewName);
165 
166 
167     /**
168     * @brief 遍歷某一單元格,返回所在的行和列(vector)
169     * @param[in] CycleName  要遍歷的名字
170     */
171     vector<string>CycleRangeReturnRowColumn(char* CycleName);
172 
173 
174     /**
175     * @brief 刷一行值
176     * @param[in] CycleName  要遍歷的名字
177     * @param[in] NewName1  寫入的新名字
178     * @param[in] NewName2  寫入的新名字
179     * @param[in] NewName3  寫入的新名字
180     * @param[in] NewName4  寫入的新名字
181     * @param[in] NewName5  寫入的新名字
182     * @param[in] NewName6  寫入的新名字
183     * @param[in] NewName7  寫入的新名字
184     * @param[in] NewName8  寫入的新名字
185     */
186     void ShuaValue(const char* CycleName, const char* NewName1, const char* NewName2, const char* NewName3, const char* NewName4, const char* NewName5, const char* NewName6, const char* NewName7, const char* NewName8);
187 
188 
189     /**
190     * @brief 刪除當前sheet所有內容
191     */
192     void DeleteSheetRange();
193 
194 
195     /**
196     * @brief 添加單元格框線
197     * @param[in] LineType  線的樣式:0- no line; 1-solid; 2-big dot;3-small dot;4-dash dot; 5-dash dot dot;
198     */
199     void SetRangeBorder(int LineType);
200 
201 
202     /**
203     * @brief 合並單元格
204     * @param[in] A1  起始單元格
205     * @param[in] B1  終止單元格
206     */
207     void SetRangeMerge(char* A1, char* B1);
208 
209 
210     /**
211     * @brief 拆分單元格
212     * @param[in] A1  起始單元格
213     * @param[in] B1  終止單元格
214     */
215     void SetRangeUnMerge(char* A1, char* B1);
216 
217 
218     /**
219     * @brief 清空單元格內容
220     * @param[in] A1  起始單元格
221     * @param[in] B1  終止單元格
222     */
223     void ClearContents(char* A1, char* B1);
224 
225 
226     /**
227     * @brief 設置所有字體左對齊
228     * @param[in] type  類型(水平對齊:默認 1 居中 -4108, 左= -4131,右=-4152)
229     */
230     void SetFontHorizontalAlignment(int type);
231 
232 
233     /**
234     * @brief 設置單元格格式(文本)
235     */
236     void SetRangeSetting();
237 
238 
239     /**
240     * @brief 遍歷單元格中復合條件的字體類型顏色大小/單元格顏色
241     * @param[in] FontType  字體類型
242     * @param[in] FontColor  字體顏色
243     * @param[in] FontSize  字體大小
244     * @param[in] RangeColor  單元格顏色
245     */
246     void CycleFontTypeColorSizeAndRangeColor(char* FontType, int FontColor, int FontSize, int RangeColor);
247 
248 
249     /**
250     * @brief 插入圖片
251     * @param[in] ExcalPath  存儲圖片文件的路徑字符串
252     * @param[in] ExcalPath  表示要連接到的文件
253     * @param[in] ExcalPath  表示將圖片與文檔一起保存
254     * @param[in] ExcalPath  圖片插入位置的左上角橫坐標
255     * @param[in] ExcalPath  圖片插入位置的左上角縱坐標
256     * @param[in] ExcalPath  表示插入的圖片的顯示寬度
257     * @param[in] ExcalPath  表示插入的圖片的顯示高度
258     */
259     void AddPicture(const char* Filename, long LinkToFile, long SaveWithDocument, float Left, float Top, float Width, float Height);
260 
261 private:
262 
263     bool IsOpenBook;
264     bool IsOpenSheet;
265 
266     //Excel應用程序
267     CApplication ExcelApp;
268     //Excel工作簿
269     CWorkbooks ExcelBooks;
270     CWorkbook ExcelBook;
271     //Excel工作表
272     CWorksheets ExcelSheets;
273     CWorksheet ExcelSheet;
274     //Excel單元格
275     CRange ExcelRange;
276     //Excel字體
277     CFont0 ft;
278     //顏色
279     Cnterior it;
280     //圖片
281     CShapes shp;
282 
283 };
View Code

 

cpp

  1 #include "stdafx.h"
  2 #include "ExcelApi.h"
  3 
  4 COleVariant covOptional((long)DISP_E_PARAMNOTFOUND, VT_ERROR);
  5 
  6 
  7 ExcelApi::ExcelApi(void)
  8 {
  9     IsOpenBook = false;
 10     IsOpenSheet = false;
 11 }
 12 
 13 ExcelApi::~ExcelApi()
 14 {
 15 }
 16 
 17 
 18 // 初始化Excel OLE
 19 BOOL ExcelApi::InitExcel()
 20 {
 21     // 初始化COM庫
 22     CoInitialize(NULL);
 23     // 初始化Excel
 24     if (!ExcelApp.CreateDispatch("Excel.Application", NULL))return FALSE;
 25     ExcelApp.put_DisplayAlerts(FALSE);       // 屏蔽警告
 26     return TRUE;
 27 }
 28 
 29 
 30 //創建EXCEL
 31 void ExcelApi::CreateExcel(const char* ExcalPath)
 32 {
 33     LPDISPATCH lpDisp;
 34     COleVariant vResult;
 35     COleVariant
 36         covTrue((short)FALSE),
 37         covFalse((short)FALSE),
 38         covOptional((long)DISP_E_PARAMNOTFOUND, VT_ERROR);
 39 
 40     if (!ExcelApp.CreateDispatch("Excel.Application"))
 41     {
 42         AfxMessageBox("創建Excel服務失敗!");
 43     }
 44 
 45     ExcelApp.put_Visible(FALSE);          //使Excel可見
 46     ExcelApp.put_UserControl(TRUE);// 設置表格狀態為用戶不可控制
 47     ExcelApp.put_DisplayAlerts(false);
 48 
 49     //打開fullFileName
 50     lpDisp = ExcelApp.get_Workbooks();
 51     ExcelBooks.AttachDispatch(lpDisp);
 52 
 53     COleVariant valTemp((long)DISP_E_PARAMNOTFOUND, VT_ERROR);
 54     lpDisp = ExcelBooks.Add(valTemp);
 55     ExcelBook.AttachDispatch(lpDisp);
 56 
 57     ExcelSheets.AttachDispatch(ExcelBook.get_Worksheets());
 58     ExcelSheet.AttachDispatch(ExcelSheets.get_Item(COleVariant((short)1)));   //獲取sheet1
 59     ExcelSheet.put_Name("TestName");     //設置sheet1名字
 60 
 61     //另存為
 62     ExcelBook.SaveAs(COleVariant(ExcalPath), covOptional, covOptional, covOptional,
 63         covOptional, covOptional, 0, covOptional, covOptional, covOptional, covOptional, covOptional);
 64     IsOpenBook = true;
 65 }
 66 
 67 
 68 //打開Excel
 69 BOOL ExcelApi::OpenFile(const char* filePath, bool type)
 70 {
 71     if (!ExcelApp.CreateDispatch("Excel.Application"))
 72     {
 73         AfxMessageBox("創建Excel服務失敗!");
 74     }
 75     ExcelApp.put_Visible(type);//使Excel可見
 76     ExcelApp.put_UserControl(FALSE);// 設置表格狀態為用戶不可控制
 77     LPDISPATCH lpDisp = NULL;
 78     lpDisp = ExcelApp.get_Workbooks();
 79 
 80     ExcelBooks.AttachDispatch(lpDisp);
 81     lpDisp = ExcelBooks.Open(filePath, covOptional, covOptional, covOptional, covOptional,
 82         covOptional, covOptional, covOptional, covOptional, covOptional, covOptional,
 83         covOptional, covOptional, covOptional, covOptional);
 84     if (lpDisp == NULL)
 85     {
 86         return FALSE;
 87     }
 88     ExcelBook.AttachDispatch(lpDisp);
 89     IsOpenBook = true;
 90     return TRUE;
 91 }
 92 
 93 void ExcelApi::CloseExcel()
 94 {
 95     ExcelRange.ReleaseDispatch();
 96     ExcelSheet.ReleaseDispatch();
 97     ExcelSheets.ReleaseDispatch();
 98     ExcelBook.ReleaseDispatch();
 99     ExcelBooks.ReleaseDispatch();
100     ExcelApp.Quit();
101     ExcelApp.ReleaseDispatch();
102 }
103 
104 
105 void ExcelApi::Save()
106 {
107     ExcelBook.Save();
108 }
109 
110 
111 int ExcelApi::GetSheetCount()
112 {
113     if (IsOpenBook != true)
114     {
115         AfxMessageBox("請先打開工作簿!");
116         return -1;
117     }
118 
119     LPDISPATCH lpDisp = NULL;
120     lpDisp = ExcelBook.get_Sheets();
121     if (lpDisp == NULL)
122     {
123         return -1;
124     }
125     ExcelSheets.AttachDispatch(lpDisp);
126 
127     return ExcelSheets.get_Count();
128 }
129 
130 
131 //設置當前工作表
132 BOOL ExcelApi::SetCurrentSheetByNum(const int& id)
133 {
134     if (IsOpenBook != true)
135     {
136         AfxMessageBox("請先打開工作簿!");
137         return FALSE;
138     }
139 
140     LPDISPATCH lpDisp = NULL;
141     lpDisp = ExcelBook.get_Sheets();
142     if (lpDisp == NULL)
143     {
144         return FALSE;
145     }
146     ExcelSheets.AttachDispatch(lpDisp);
147     lpDisp = ExcelSheets.get_Item(COleVariant((short)id));
148     if (lpDisp == NULL)
149     {
150         return FALSE;
151     }
152     ExcelSheet.AttachDispatch(lpDisp);
153     ExcelSheet.Activate();
154     IsOpenSheet = true;
155     return TRUE;
156 }
157 BOOL ExcelApi::SetCurrentSheetByName(string sheet_name)
158 {
159     if (IsOpenBook != true)
160     {
161         AfxMessageBox("請先打開工作簿!");
162         return FALSE;
163     }
164 
165     LPDISPATCH lpDisp = NULL;
166     lpDisp = ExcelBook.get_Sheets();
167     if (lpDisp == NULL)
168     {
169         return FALSE;
170     }
171     ExcelSheets.AttachDispatch(lpDisp);
172 
173     int count = GetSheetCount();
174     string name;
175     int id;
176     for (int i = 0; i < count; i++)
177     {
178         id = i + 1;
179         SetCurrentSheetByNum(id);
180         name = GetSheetName();
181         if (sheet_name == name)
182         {
183             lpDisp = ExcelSheets.get_Item(COleVariant((short)id));
184             break;
185         }
186     }
187 
188 
189     if (lpDisp == NULL)
190     {
191         return FALSE;
192     }
193     ExcelSheet.AttachDispatch(lpDisp);
194     ExcelSheet.Activate();
195     IsOpenSheet = true;
196     return TRUE;
197 }
198 
199 
200 string ExcelApi::GetRangeData(const int row, const int column)
201 {
202     //獲得使用的區域Range(區域)
203     ExcelRange.AttachDispatch(ExcelSheet.get_UsedRange(), TRUE);
204 
205     // 讀取
206     CRange range;
207     range.AttachDispatch(ExcelRange.get_Item(COleVariant((long)row), COleVariant((long)column)).pdispVal);
208     COleVariant vResult = range.get_Value2();
209     range.ReleaseDispatch();
210     // 分析vResult
211     CString str;
212     if (vResult.vt == VT_BSTR)str = vResult.bstrVal;                    // 字符串 
213     else if (vResult.vt == VT_INT)str.Format(_T("%d"), vResult.pintVal);    // 整數
214     else if (vResult.vt == VT_R8)str.Format(_T("%.3f"), vResult.dblVal);    // 8字節的整數
215     else if (vResult.vt == VT_DATE)                                        // 時間格式
216     {
217         SYSTEMTIME st; VariantTimeToSystemTime(vResult.date, &st);
218         CTime tm(st);    str = tm.Format("%Y-%m-%d");
219     }
220     else if (vResult.vt == VT_EMPTY)str = "";                            // 空的單元格
221     else str = "";
222     return str;
223 }
224 
225 
226 
227 string ExcelApi::GetSheetName()
228 {
229     if (IsOpenBook != true)
230     {
231         AfxMessageBox("請先打開工作簿!");
232         return "false";
233     }
234 
235     return ExcelSheet.get_Name();
236 }
237 
238 
239 
240 void ExcelApi::SetSheetName(const int SheetNum, const char* SheetName)
241 {
242     ExcelSheets.AttachDispatch(ExcelBook.get_Worksheets());
243     ExcelSheet.AttachDispatch(ExcelSheets.get_Item(COleVariant((short)SheetNum)));   //獲取sheet1
244     ExcelSheet.put_Name(SheetName);     //設置sheet1名字
245 }
246 
247 
248 
249 //當前sheet單元格寫入內容
250 void ExcelApi::SetRangeData(const int row, const int column, const char* Data)
251 {
252     if (IsOpenBook != true)
253     {
254         AfxMessageBox("請先打開工作簿!");
255         return;
256     }
257 
258     //得到全部Cells,此時,userRange是cells的集合
259     ExcelRange.AttachDispatch(ExcelSheet.get_Cells(), TRUE);
260 
261     //設置表格內容
262     ExcelRange.put_Item(COleVariant((long)row), COleVariant((long)column), COleVariant(_T(Data)));
263 
264 }
265 
266 
267 //獲得當前sheet使用的行數
268 int ExcelApi::GetRowNum()
269 {
270     if (IsOpenBook != true)
271     {
272         AfxMessageBox("請先打開工作簿!");
273         return 0;
274     }
275 
276     //獲得使用的區域Range(區域)
277     ExcelRange.AttachDispatch(ExcelSheet.get_UsedRange(), TRUE);
278 
279     //獲得使用的行數
280     long lgUsedRowNum = 1;
281     ExcelRange.AttachDispatch(ExcelRange.get_Rows(), TRUE);
282     lgUsedRowNum = ExcelRange.get_Count();
283 
284     return lgUsedRowNum;
285 }
286 
287 
288 
289 int ExcelApi::GetColumnNum()
290 {
291     if (IsOpenBook != true)
292     {
293         AfxMessageBox("請先打開工作簿!");
294         return 0;
295     }
296 
297     //獲得使用的區域Range(區域)
298     ExcelRange.AttachDispatch(ExcelSheet.get_UsedRange(), TRUE);
299 
300     //獲得使用的列數
301     long lgUsedColumnNum = 1;
302     ExcelRange.AttachDispatch(ExcelRange.get_Columns(), TRUE);
303     lgUsedColumnNum = ExcelRange.get_Count();
304 
305     return lgUsedColumnNum;
306 }
307 
308 
309 void ExcelApi::DeleteRange(char* A1, char* B1, int type)
310 {
311     //方法1    
312     //ExcelRange.AttachDispatch(ExcelSheet.get_Range(COleVariant(_T(A1)), COleVariant(_T(B1))), TRUE);//設置單元格區域
313     //ExcelRange.AttachDispatch(ExcelRange.get_EntireRow());//獲取這一行
314     //ExcelRange.Delete(vtMissing);//刪除這一行
315 
316     //方法2
317     ExcelRange.AttachDispatch(ExcelSheet.get_Range(COleVariant(_T(A1)), COleVariant(_T(B1))), TRUE);//設置單元格區域
318     ExcelRange.Delete(COleVariant((long)type));//設置刪除類型1.右側單元格左移 2.下方單元格上移 3.整行 4.整列
319 }
320 
321 void ExcelApi::AddRange(char* A1, char* B1, int type)
322 {
323     //方法1
324     //ExcelRange.AttachDispatch(ExcelSheet.get_Range(COleVariant(_T("F3")), COleVariant(_T("G3"))), TRUE);//設置單元格區域
325     //ExcelRange.AttachDispatch(ExcelRange.get_EntireRow());//獲取這一行
326     //ExcelRange.Insert(vtMissing, vtMissing);//在上面添加新一行
327 
328     //方法2
329     ExcelRange.AttachDispatch(ExcelSheet.get_Range(COleVariant(_T(A1)), COleVariant(_T(B1))), TRUE);//設置單元格區域
330     //   ExcelRange.Insert(COleVariant((long)type), vtMissing);//設置添加類型1.活動單元格右移 2.活動單元格下移 3.整行 4.整列
331 
332 }
333 
334 
335 void ExcelApi::SetFont(char* A1, char* B1, char* FontType, int FontColor, int FontSize)
336 {
337     //設置字體顏色
338     ExcelRange.AttachDispatch(ExcelSheet.get_Range(COleVariant(_T(A1)), COleVariant(_T(B1))), TRUE);//設置單元格區域
339     ft.AttachDispatch(ExcelRange.get_Font());
340     ft.put_Name(COleVariant(_T(FontType)));//設置字體類型
341     ft.put_ColorIndex(COleVariant((long)FontColor));//設置字體顏色    
342     ft.put_Size(COleVariant((long)FontSize));//設置字體大小
343 }
344 
345 void ExcelApi::SetRangeColor(char* A1, char* B1, int RangeColor)
346 {
347     //設置單元格顏色
348     ExcelRange.AttachDispatch(ExcelSheet.get_Range(COleVariant(_T(A1)), COleVariant(_T(B1))), TRUE);//設置單元格區域
349 
350     //設置單元格填充顏色
351     it.AttachDispatch(ExcelRange.get_Interior());
352     it.put_ColorIndex(_variant_t((long)RangeColor));
353 }
354 
355 
356 void ExcelApi::CycleFontTypeColorSizeAndRangeColor(char* FontType, int FontColor, int FontSize, int RangeColor)
357 {
358     //獲得使用的區域Range(區域)
359     ExcelRange.AttachDispatch(ExcelSheet.get_UsedRange(), TRUE);
360 
361     //獲得使用的行數
362     long lgUsedRowNum = 1;
363     ExcelRange.AttachDispatch(ExcelRange.get_Rows(), TRUE);
364     lgUsedRowNum = ExcelRange.get_Count();
365 
366     //獲得使用的列數
367     long lgUsedColumnNum = 1;
368     ExcelRange.AttachDispatch(ExcelRange.get_Columns(), TRUE);
369     lgUsedColumnNum = ExcelRange.get_Count();
370 
371     vector<CString> delete_all;
372     //遍歷整個Excel表格
373     for (int j = 1; j <= lgUsedRowNum; j++)
374     {
375         for (int i = 1; i <= lgUsedColumnNum; i++)
376         {
377             CString str1;
378             str1.Format("%c%d", 65 + i - 1, j);
379             //LPDISPATCH lpDisp = ExcelRange.get_Range(COleVariant(str1), COleVariant(str1));
380 
381             //設置字體顏色
382             ExcelRange.AttachDispatch(ExcelSheet.get_Range(COleVariant(_T(str1)), COleVariant(_T(str1))), TRUE);//設置單元格區域
383             ft.AttachDispatch(ExcelRange.get_Font());
384             //讀取字體顏色
385             VARIANT vResult1 = ft.get_ColorIndex();
386             CString str0;
387             if (vResult1.vt == VT_I4)str0.Format(_T("%d"), vResult1.iVal);    // 8字節的整數
388 
389             //讀取字體類型
390             VARIANT vResult2 = ft.get_Name();
391             CString str2;
392             if (vResult2.vt == VT_BSTR)str2 = vResult2.bstrVal;
393 
394             //讀取字體大小
395             VARIANT vResult3 = ft.get_Size();
396             CString str3;
397             if (vResult3.vt == VT_R8)str3.Format(_T("%0.0f"), vResult3.dblVal);    // 8字節的整數
398 
399             //設置單元格顏色
400             ExcelRange.AttachDispatch(ExcelSheet.get_Range(COleVariant(_T(str1)), COleVariant(_T(str1))), TRUE);//設置單元格區域
401             it.AttachDispatch(ExcelRange.get_Interior());
402             //讀取單元格填充顏色
403             VARIANT vResult4 = it.get_ColorIndex();
404             CString str4;
405             if (vResult4.vt == VT_I4)str4.Format(_T("%d"), vResult4.iVal);    // 8字節的整數
406 
407             //Cstring轉char*
408             char *p = (LPSTR)(LPCTSTR)str0;
409             int AA = atoi(p);
410 
411             //Cstring轉char*
412             char *p1 = (LPSTR)(LPCTSTR)str3;
413             int AA1 = atoi(p1);
414 
415             //Cstring轉char*
416             char *p2 = (LPSTR)(LPCTSTR)str4;
417             int AA2 = atoi(p2);
418 
419             //添加到vector
420             if (AA == FontColor && AA1 == FontSize && str2 == FontType && AA2 == RangeColor)
421             {
422                 delete_all.push_back(str1);
423             }
424 
425         }
426 
427     }
428 
429     for (int i = 0; i < delete_all.size(); i++)
430     {
431         //方法2
432         ExcelRange.AttachDispatch(ExcelSheet.get_Range(COleVariant(_T(delete_all[i])), COleVariant(_T(delete_all[i]))), TRUE);//設置單元格區域
433         ExcelRange.Delete(COleVariant((long)2));//設置刪除類型1.右側單元格左移 2.下方單元格上移 3.整行 4.整列
434 
435         //添加單元格,補充進去
436         //方法2
437         ExcelRange.AttachDispatch(ExcelSheet.get_Range(COleVariant(_T(delete_all[i])), COleVariant(_T(delete_all[i]))), TRUE);//設置單元格區域
438         ExcelRange.Insert(COleVariant((long)2), vtMissing);//設置添加類型1.活動單元格右移 2.活動單元格下移 3.整行 4.整列
439     }
440 
441 }
442 
443 
444 
445 void ExcelApi::CycleRangeSetData(char* CycleName, char* NewName)
446 {
447     //獲得使用的區域Range(區域)
448     ExcelRange.AttachDispatch(ExcelSheet.get_UsedRange(), TRUE);
449 
450     //獲得使用的行數
451     long lgUsedRowNum = 1;
452     ExcelRange.AttachDispatch(ExcelRange.get_Rows(), TRUE);
453     lgUsedRowNum = ExcelRange.get_Count();
454 
455     //獲得使用的列數
456     long lgUsedColumnNum = 1;
457     ExcelRange.AttachDispatch(ExcelRange.get_Columns(), TRUE);
458     lgUsedColumnNum = ExcelRange.get_Count();
459 
460     //遍歷整個Excel表格
461     for (int j = 1; j <= lgUsedRowNum; j++)
462     {
463         for (int i = 1; i <= lgUsedColumnNum; i++)
464         {
465             CString str;
466             str.Format("%c%d", 65 + i - 1, j);
467             LPDISPATCH lpDisp = ExcelRange.get_Range(COleVariant(str), COleVariant(str));
468 
469             CRange range;
470             range.AttachDispatch(lpDisp);
471 
472             VARIANT vl = range.get_Value2();
473 
474             CString text;
475             CString text1 = CycleName;
476             if (vl.vt == VT_BSTR)       //字符串
477             {
478                 text = vl.bstrVal;
479                 if (text == text1)
480                 {
481                     //得到全部Cells,此時,userRange是cells的集合
482                     range.AttachDispatch(ExcelSheet.get_Cells(), TRUE);
483 
484                     //設置表格內容
485                     range.put_Item(COleVariant((long)j), COleVariant((long)i), COleVariant(_T(NewName)));
486 
487                 }
488 
489             }
490         }
491 
492     }
493 
494 }
495 
496 
497 
498 
499 vector<string> ExcelApi::CycleRangeReturnRowColumn(char* CycleName)
500 {
501     //創建vector
502     vector<string> RowColumnAll;
503 
504     //先清空vector
505     RowColumnAll.clear();
506 
507     //獲得使用的區域Range(區域)
508     ExcelRange.AttachDispatch(ExcelSheet.get_UsedRange(), TRUE);
509 
510     //獲得使用的行數
511     long lgUsedRowNum = 1;
512     ExcelRange.AttachDispatch(ExcelRange.get_Rows(), TRUE);
513     lgUsedRowNum = ExcelRange.get_Count();
514 
515     //獲得使用的列數
516     long lgUsedColumnNum = 1;
517     ExcelRange.AttachDispatch(ExcelRange.get_Columns(), TRUE);
518     lgUsedColumnNum = ExcelRange.get_Count();
519 
520     //遍歷整個Excel表格
521     for (int j = 1; j <= lgUsedRowNum; j++)
522     {
523         for (int i = 1; i <= lgUsedColumnNum; i++)
524         {
525             CString str;
526             str.Format("%c%d", 65 + i - 1, j);
527             LPDISPATCH lpDisp = ExcelRange.get_Range(COleVariant(str), COleVariant(str));
528 
529             CRange range;
530             range.AttachDispatch(lpDisp);
531 
532             VARIANT vl = range.get_Value2();
533 
534             CString text;
535             CString text1 = CycleName;
536             if (vl.vt == VT_BSTR)       //字符串
537             {
538                 text = vl.bstrVal;
539                 if (text == text1)
540                 {
541                     //得到全部Cells,此時,userRange是cells的集合
542                     range.AttachDispatch(ExcelSheet.get_Cells(), TRUE);
543 
544                     //得到行和列
545                     //轉換
546                     char msg[256];
547                     sprintf_s(msg, "%d", j);
548                     string AA = msg;
549 
550                     char msg1[256];
551                     sprintf_s(msg1, "%d", i);
552                     string BB = msg1;
553 
554                     //字符串拼接
555                     string RowColumn = AA + "," + BB;
556 
557                     //添加到vector
558                     RowColumnAll.push_back(RowColumn);
559                 }
560             }
561         }
562     }
563 
564     return RowColumnAll;
565 }
566 
567 
568 void ExcelApi::ShuaValue(const char* CycleName, const char* NewName1, const char* NewName2, const char* NewName3, const char* NewName4, const char* NewName5, const char* NewName6, const char* NewName7, const char* NewName8)
569 {
570     //獲得使用的區域Range(區域)
571     ExcelRange.AttachDispatch(ExcelSheet.get_UsedRange(), TRUE);
572 
573     //獲得使用的行數
574     long lgUsedRowNum = 1;
575     ExcelRange.AttachDispatch(ExcelRange.get_Rows(), TRUE);
576     lgUsedRowNum = ExcelRange.get_Count();
577 
578     //獲得使用的列數
579     long lgUsedColumnNum = 1;
580     ExcelRange.AttachDispatch(ExcelRange.get_Columns(), TRUE);
581     lgUsedColumnNum = ExcelRange.get_Count();
582 
583     //遍歷整個Excel表格
584     for (int j = 1; j <= lgUsedRowNum; j++)
585     {
586         for (int i = 1; i <= lgUsedColumnNum; i++)
587         {
588             CString str;
589             str.Format("%c%d", 65 + i - 1, j);
590             LPDISPATCH lpDisp = ExcelRange.get_Range(COleVariant(str), COleVariant(str));
591 
592             CRange range;
593             range.AttachDispatch(lpDisp);
594 
595             VARIANT vl = range.get_Value2();
596 
597             CString text;
598             CString text1 = CycleName;
599             if (vl.vt == VT_BSTR)       //字符串
600             {
601                 text = vl.bstrVal;
602                 if (text == text1)
603                 {
604                     if (i == 6)
605                     {
606                         //得到全部Cells,此時,userRange是cells的集合
607                         range.AttachDispatch(ExcelSheet.get_Cells(), TRUE);
608 
609                         //設置表格內容
610                         range.put_Item(COleVariant((long)j), COleVariant((long)i), COleVariant(_T(NewName1)));
611                         range.put_Item(COleVariant((long)j), COleVariant((long)i + 1), COleVariant(_T(NewName2)));
612                         range.put_Item(COleVariant((long)j), COleVariant((long)i + 2), COleVariant(_T(NewName3)));
613                         range.put_Item(COleVariant((long)j), COleVariant((long)i + 3), COleVariant(_T(NewName4)));
614                         range.put_Item(COleVariant((long)j), COleVariant((long)i + 4), COleVariant(_T(NewName5)));
615                         range.put_Item(COleVariant((long)j), COleVariant((long)i + 5), COleVariant(_T(NewName6)));
616                         //range.put_Item(COleVariant((long)j), COleVariant((long)i + 6), COleVariant(_T(NewName7)));
617                         //range.put_Item(COleVariant((long)j), COleVariant((long)i + 7), COleVariant(_T(NewName8)));
618 
619                         //轉換
620                         char F[256];
621                         sprintf_s(F, "F%d", j);
622 
623                         char M[256];
624                         sprintf_s(M, "M%d", j);
625 
626                         //設置字體顏色
627                         range.AttachDispatch(ExcelSheet.get_Range(COleVariant(_T(F)), COleVariant(_T(M))), TRUE);
628                         ft.AttachDispatch(range.get_Font());
629                         ft.put_Name(COleVariant(_T("宋體")));
630                         ft.put_ColorIndex(COleVariant((long)1));    //顏色    
631                         ft.put_Size(COleVariant((long)11));         //大小
632 
633                         //設置單元格填充顏色
634                         it.AttachDispatch(range.get_Interior());
635                         //                        it.put_ColorIndex(_variant_t((long)39));
636                     }
637 
638 
639                 }
640 
641             }
642         }
643 
644     }
645 
646 
647 }
648 
649 
650 
651 
652 
653 void ExcelApi::DeleteSheetRange()
654 {
655     //獲得使用的區域Range(區域)
656     ExcelRange.AttachDispatch(ExcelSheet.get_UsedRange(), TRUE);
657 
658     //獲得使用的行數
659     long lgUsedRowNum = 1;
660     ExcelRange.AttachDispatch(ExcelRange.get_Rows(), TRUE);
661     lgUsedRowNum = ExcelRange.get_Count();
662 
663     //獲得使用的列數
664     long lgUsedColumnNum = 1;
665     ExcelRange.AttachDispatch(ExcelRange.get_Columns(), TRUE);
666     lgUsedColumnNum = ExcelRange.get_Count();
667 
668     char msg[256];
669     sprintf_s(msg, "M%d", lgUsedRowNum);
670 
671     //方法2
672     ExcelRange.AttachDispatch(ExcelSheet.get_Range(COleVariant(_T("A1")), COleVariant(_T(msg))), TRUE);//設置單元格區域
673     ExcelRange.Delete(COleVariant((long)3));//設置刪除類型1.右側單元格左移 2.下方單元格上移 3.整行 4.整列
674 
675 }
676 
677 
678 
679 void ExcelApi::SetRangeBorder(int LineType)
680 {
681     //獲得使用的區域Range(區域)
682     ExcelRange.AttachDispatch(ExcelSheet.get_UsedRange(), TRUE);
683 
684     //獲得使用的行數
685     long lgUsedRowNum = 1;
686     ExcelRange.AttachDispatch(ExcelRange.get_Rows(), TRUE);
687     lgUsedRowNum = ExcelRange.get_Count();
688 
689     //獲得使用的列數
690     long lgUsedColumnNum = 1;
691     ExcelRange.AttachDispatch(ExcelRange.get_Columns(), TRUE);
692     lgUsedColumnNum = ExcelRange.get_Count();
693 
694     //畫邊框線
695     VARIANT vRange1, vRange2, vRange3, vRange4, vRange5;
696     VariantInit(&vRange1);
697     VariantInit(&vRange2);
698     VariantInit(&vRange3);
699     VariantInit(&vRange4);
700     VariantInit(&vRange5);
701     vRange1.vt = VT_I2;
702     vRange1.lVal = LineType;   // 線的樣式:0- no line; 1-solid; 2-big dot;3-small dot;4-dash dot; 5-dash dot dot;
703     vRange2.vt = VT_I2;
704     vRange2.lVal = 2;  // 線的粗細程度;
705     vRange3.vt = VT_I2;
706     vRange3.lVal = 1;   // 1-black;2-white;3-red;4-green;5-blue; 6-yellow; 7-pink;8-dark blue;
707     vRange4.vt = VT_UI4;
708     vRange4.uintVal = RGB(0, 0, 0);  // 我測試后認為,沒有實際意義,只有vRange3起作用
709     vRange5.vt = VT_I2;
710     vRange5.lVal = 1;
711 
712     //遍歷整個Excel表格
713     for (int j = 1; j <= lgUsedRowNum; j++)
714     {
715         for (int i = 1; i <= lgUsedColumnNum; i++)
716         {
717             CString str;
718             str.Format("%c%d", 65 + i - 1, j);
719             LPDISPATCH lpDisp = ExcelRange.get_Range(COleVariant(str), COleVariant(str));
720 
721             CRange range;
722             range.AttachDispatch(lpDisp);
723 
724             //畫邊框線
725             range.BorderAround(vRange1, vRange2.lVal, vRange3.lVal, vRange4, vRange5);
726 
727         }
728 
729     }
730 
731 }
732 
733 
734 
735 void ExcelApi::SetRangeMerge(char* A1, char* B1)
736 {
737     ExcelRange.AttachDispatch(ExcelSheet.get_Range(COleVariant(_T(A1)), COleVariant(_T(B1))), TRUE);//設置單元格區域
738     ExcelRange.Merge(COleVariant((long)0));
739 }
740 
741 
742 
743 void ExcelApi::SetRangeUnMerge(char* A1, char* B1)
744 {
745     ExcelRange.AttachDispatch(ExcelSheet.get_Range(COleVariant(_T(A1)), COleVariant(_T(B1))), TRUE);//設置單元格區域
746     ExcelRange.UnMerge();
747 }
748 
749 
750 
751 void ExcelApi::ClearContents(char* A1, char* B1)
752 {
753     ExcelRange.AttachDispatch(ExcelSheet.get_Range(COleVariant(_T(A1)), COleVariant(_T(B1))), TRUE);//設置單元格區域
754     ExcelRange.ClearContents();
755 }
756 
757 
758 
759 void ExcelApi::SetFontHorizontalAlignment(int type)
760 {
761     //獲得使用的區域Range(區域)
762     ExcelRange.AttachDispatch(ExcelSheet.get_UsedRange(), TRUE);
763 
764     int num = 0;
765     if (type == 1)
766     {
767         num = -4108;
768     }
769     else if (true)
770     {
771         num = -4131;
772     }
773     else if (true)
774     {
775         num = -4152;
776     }
777     //設置對齊方式
778     //水平對齊:默認 1 居中 -4108, 左= -4131,右=-4152
779     //垂直對齊:默認 2 居中 -4108, 左= -4160,右=-4107
780     //ExcelRange.put_VerticalAlignment(COleVariant((long)-4108));
781     ExcelRange.put_HorizontalAlignment(COleVariant((long)num));
782 
783 }
784 
785 
786 void ExcelApi::SetRangeSetting()
787 {
788     //獲得使用的區域Range(區域)
789     ExcelRange.AttachDispatch(ExcelSheet.get_UsedRange(), TRUE);
790 
791     //設置單元格格式為文本
792     ExcelRange.put_NumberFormatLocal(COleVariant("@"));
793 
794 }
795 
796 
797 void ExcelApi::AddPicture(const char* Filename, long LinkToFile, long SaveWithDocument, float Left, float Top, float Width, float Height)
798 {
799     //獲得使用的區域
800     shp.AttachDispatch(ExcelSheet.get_Shapes());
801 
802     //插入圖片
803     shp.AddPicture(Filename,LinkToFile,SaveWithDocument,Left,Top,Width,Height);
804 }
View Code

 

stdafx.h

 1 // stdafx.h : 標准系統包含文件的包含文件,
 2 // 或是經常使用但不常更改的
 3 // 特定於項目的包含文件
 4 
 5 #pragma once
 6 
 7 #ifndef VC_EXTRALEAN
 8 #define VC_EXTRALEAN            // 從 Windows 頭中排除極少使用的資料
 9 #endif
10 
11 //#include "targetver.h"
12 
13 #define _ATL_CSTRING_EXPLICIT_CONSTRUCTORS      // 某些 CString 構造函數將是顯式的
14 
15 // 關閉 MFC 對某些常見但經常可放心忽略的警告消息的隱藏
16 #define _AFX_ALL_WARNINGS
17 
18 #include <afxwin.h>         // MFC 核心組件和標准組件
19 #include <afxext.h>         // MFC 擴展
20 
21 
22 #include <afxdisp.h>        // MFC 自動化類
23 
24 
25 
26 #ifndef _AFX_NO_OLE_SUPPORT
27 #include <afxdtctl.h>           // MFC 對 Internet Explorer 4 公共控件的支持
28 #endif
29 #ifndef _AFX_NO_AFXCMN_SUPPORT
30 #include <afxcmn.h>             // MFC 對 Windows 公共控件的支持
31 #endif // _AFX_NO_AFXCMN_SUPPORT
32 
33 #include <afxcontrolbars.h>     // 功能區和控件條的 MFC 支持
34 
35 
36 
37 
38 
39 
40 
41 
42 
43 #ifdef _UNICODE
44 #if defined _M_IX86
45 #pragma comment(linker,"/manifestdependency:\"type='win32' name='Microsoft.Windows.Common-Controls' version='6.0.0.0' processorArchitecture='x86' publicKeyToken='6595b64144ccf1df' language='*'\"")
46 #elif defined _M_X64
47 #pragma comment(linker,"/manifestdependency:\"type='win32' name='Microsoft.Windows.Common-Controls' version='6.0.0.0' processorArchitecture='amd64' publicKeyToken='6595b64144ccf1df' language='*'\"")
48 #else
49 #pragma comment(linker,"/manifestdependency:\"type='win32' name='Microsoft.Windows.Common-Controls' version='6.0.0.0' processorArchitecture='*' publicKeyToken='6595b64144ccf1df' language='*'\"")
50 #endif
51 #endif
View Code

stdafx.cpp

1 // stdafx.cpp : 只包括標准包含文件的源文件
2 // MFCApplication1.pch 將作為預編譯頭
3 // stdafx.obj 將包含預編譯類型信息
4 
5 #include "stdafx.h"
View Code

 

調用

ExcelApi *SetExcelApi = new ExcelApi();


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM