word表格设置如下:

注意,表格需要设置 开始结束标记:TableStartTableEnd:

1
2
3
4
5
6
7
8
9
TableStart:GZ // 开始,GZ为表名

T_Row_QZSJ
T_Row_ZW
T_Row_GZDW
T_Row_LZYY
T_Row_ZMR

TableEnd:GZ // 结束,GZ为表名

word设置表格如下:

微信截图_20210830154308.png

微信截图_20210830153642.png

调用方法:

Dev开发界面方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
private Dictionary<string, string> familyMembersDic = new Dictionary<string, string>(8);

private void GenFamilyMembers()
{
if (familyMembersDic.Keys.Count == 8) return;

familyMembersDic.Add("父", "");
familyMembersDic.Add("母", "");
familyMembersDic.Add("配偶", "");
familyMembersDic.Add("子女", "");
familyMembersDic.Add("(配偶)父", "");
familyMembersDic.Add("(配偶)母", "");
familyMembersDic.Add("兄弟", "");
familyMembersDic.Add("姐妹", "");
}

/// <summary>
/// 导出人员情况登记表
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void simpleButton1_Click(object sender, EventArgs e)
{
try
{
FolderBrowserDialog folderDialog = new FolderBrowserDialog();
folderDialog.Description = "选择路径";
DialogResult dialogResult = folderDialog.ShowDialog();
if (dialogResult == DialogResult.Cancel) return;
string path = folderDialog.SelectedPath;

var templateFile = Environment.CurrentDirectory + @"\Template\WordsTemp\01人员情况登记表.doc";

GenFamilyMembers();

//打开流转单模板
WordHelper wh = new WordHelper(templateFile);

bool isGen = false;
for (int i = 0; i < this.dgvGroup.RowCount; i++)
{
if (this.dgvGroup.GetRow(i) is TB_PLY_OPT_EHR_ResumeInfoDtoView row )
{
var t_time = $"{row.createDateTime:yyyy-MM-dd}";
wh.ReplaceText("T_name", row.name);
wh.ReplaceText("T_jobtitle", row.jobtitle);
wh.ReplaceText("T_date", t_time);
wh.ReplaceText("T_gender", row.gender);
wh.ReplaceText("T_idcard", row.idcard);
wh.ReplaceText("T_birth", row.birth);
wh.ReplaceText("T_mz", row.national);
wh.ReplaceText("T_nativeplace", row.nativeplace);
wh.ReplaceText("T_hkszd", row.censusregisterseat);
wh.ReplaceText("T_sg", row.uheight.ToString());
wh.ReplaceText("T_married", row.married);
wh.ReplaceText("T_health", row.health);
wh.ReplaceText("T_zy", row.lastSpeciality);
wh.ReplaceText("T_school", row.school);
wh.ReplaceText("T_bysj", row.endDate);
wh.ReplaceText("T_xl", row.academicDegree);
wh.ReplaceText("T_phone", row.phone);
wh.ReplaceText("T_jtdh", row.homephone);
wh.ReplaceText("T_zc", row.thetitle);
wh.ReplaceText("T_currentaddress", row.currentaddress);

DataTable dtXM = new DataTable("Family");
dtXM.Columns.Add("T_Row_Gx", typeof(string));
dtXM.Columns.Add("T_Row_Xm", typeof(string));
dtXM.Columns.Add("T_Row_IdCard", typeof(string));
dtXM.Columns.Add("T_Row_Work", typeof(string));
dtXM.Columns.Add("T_Row_Phone", typeof(string));
if (row.家庭成员 != null && row.家庭成员.Any())
{
foreach (var dic in familyMembersDic)
{
var item = row.家庭成员.FirstOrDefault(o => o.与应聘者关系 == dic.Key);

DataRow dr = dtXM.NewRow();
if (item == null)
{
dr["T_Row_Gx"] = dic.Key;
dr["T_Row_Xm"] = "";
dr["T_Row_IdCard"] = "";
dr["T_Row_Work"] = "";
dr["T_Row_Phone"] = "";
}
else
{
dr["T_Row_Gx"] = item.与应聘者关系;
dr["T_Row_Xm"] = item.姓名;
dr["T_Row_IdCard"] = item.身份证号;
dr["T_Row_Work"] = item.工作单位及职务;
dr["T_Row_Phone"] = item.联系电话;
}
dtXM.Rows.Add(dr);
}
}
wh.doc.MailMerge.ExecuteWithRegions(dtXM);

DataTable dtEdu = new DataTable("Edu");
dtEdu.Columns.Add("T_Row_QZSJ", typeof(string));
dtEdu.Columns.Add("T_Row_School", typeof(string));
dtEdu.Columns.Add("T_Row_ZY", typeof(string));
if (row.学业经历 != null && row.学业经历.Any())
{
foreach (var item in row.学业经历)
{
DataRow dr = dtEdu.NewRow();

dr["T_Row_QZSJ"] = item.起止年月;
dr["T_Row_School"] = item.学校名称;
dr["T_Row_ZY"] = item.所学专业;

dtEdu.Rows.Add(dr);
}
}
wh.doc.MailMerge.ExecuteWithRegions(dtEdu);

DataTable dtGZ = new DataTable("GZ");
dtGZ.Columns.Add("T_Row_QZSJ", typeof(string));
dtGZ.Columns.Add("T_Row_ZW", typeof(string));
dtGZ.Columns.Add("T_Row_GZDW", typeof(string));
dtGZ.Columns.Add("T_Row_LZYY", typeof(string));
dtGZ.Columns.Add("T_Row_ZMR", typeof(string));
if (row.工作经历 != null && row.工作经历.Any())
{
foreach (var item in row.工作经历)
{
DataRow dr = dtGZ.NewRow();

dr["T_Row_QZSJ"] = item.起止年月;
dr["T_Row_ZW"] = item.职务;
dr["T_Row_GZDW"] = item.工作单位;
dr["T_Row_LZYY"] = item.离职原因;
dr["T_Row_ZMR"] = item.证明人及其联系电话;

dtGZ.Rows.Add(dr);
}
}
wh.doc.MailMerge.ExecuteWithRegions(dtGZ);

wh.SaveWord($@"{path}\\{row.name}_{DateTime.Now:yyyyMMddhhmmss}.doc");
isGen = true;
}
}
if (isGen)
{
if (DevExpress.XtraEditors.XtraMessageBox.Show("保存成功,是否打开文件夹?", "提示", MessageBoxButtons.YesNo,
MessageBoxIcon.Information) == DialogResult.Yes)
System.Diagnostics.Process.Start("explorer.exe", path); //打开指定路径
}
else
{
DevExpress.XtraEditors.XtraMessageBox.Show("未能生成有效文档");
}
}
catch (Exception ex)
{
DevExpress.XtraEditors.XtraMessageBox.Show(ex.Message);
}
}
AsposeWordHelper帮助类
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
using Aspose.Pdf.Facades;
using Aspose.Pdf.InteractiveFeatures.Forms;
using Aspose.Words;
using Aspose.Words.Drawing;
using Aspose.Words.Saving;
using Aspose.Words.Tables;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Net;
using System.Text.RegularExpressions;

namespace Utils
{
public class AsposeWordHelper
{
/// <summary>
/// 模板
/// </summary>
public string templateFile { get; set; }

public Document doc = null;
public DocumentBuilder builder = null;

#region 实例化模板

public WordHelper(string templateFile)
{
doc = new Document(templateFile); //载入模板
builder = new DocumentBuilder(doc);
//doc.Protect(ProtectionType.ReadOnly); //设为只读
}

#endregion 实例化模板

/// <summary>
/// 替换书签内容,传入书签名称和要替换的值即可
/// </summary>
public void ReplaceBookmarks(string BookmarksName, string ReplaceBookmarksText)
{
if (doc.Range.Bookmarks[BookmarksName] != null)
{
Aspose.Words.Bookmark mark = doc.Range.Bookmarks[BookmarksName];
mark.Text = ReplaceBookmarksText;
}
}

/// <summary>
/// 替换书签图片,传入书签名称和要替换的值及宽和高即可,会判断远程文件是否存在,适用于报告生成。
/// </summary>
public void ReplaceBookmarksPic(string BookmarksName, string ReplaceBookmarksPic, int picWidth, int picHeight)
{
if (RemoteFileExists(ReplaceBookmarksPic))
{
Shape shape = new Shape(doc, ShapeType.Image);
shape.ImageData.SetImage(ReplaceBookmarksPic);
shape.Width = picWidth;
shape.Height = picHeight;

builder.MoveToBookmark(BookmarksName);
builder.InsertNode(shape);
}
}

/// <summary>
/// 替换书签图片,传入书签名称和要替换的值及宽和高即可,不用判断文件是否存在!
/// </summary>
public void ReplaceBookmarksPic1(string BookmarksName, string ReplaceBookmarksPic, int picWidth, int picHeight)
{
Shape shape = new Shape(doc, ShapeType.Image);
shape.ImageData.SetImage(ReplaceBookmarksPic);
shape.Width = picWidth;
shape.Height = picHeight;
builder.MoveToBookmark(BookmarksName);
builder.InsertNode(shape);
}

public void ReplaceBookmarksPic1(string BookmarksName, byte[] imageData, int picWidth, int picHeight, double picLeft)
{
Shape shape = new Shape(doc, ShapeType.Image);
shape.ImageData.SetImage(imageData);
shape.Width = picWidth;
shape.Height = picHeight;
shape.Left = picLeft;
builder.MoveToBookmark(BookmarksName);
builder.InsertNode(shape);
}

public void ReplaceBookmarksPic1(string BookmarksName, string ReplaceBookmarksPic, int picWidth, int picHeight, double picLeft)
{
Shape shape = new Shape(doc, ShapeType.Image);
shape.ImageData.SetImage(ReplaceBookmarksPic);
shape.Width = picWidth;
shape.Height = picHeight;
shape.Left = picLeft;

builder.MoveToBookmark(BookmarksName);
builder.InsertNode(shape);
}

/// <summary>
/// 插入图片,传入书签名称和要替换的值及左侧位置及宽和高即可,不用判断文件是否存在。未测试!!!!
/// </summary>
public void ReplaceBookmarksPic2(string BookmarksName, string ReplaceBookmarksPic, double picLeft, double picWidth, double picHeight)
{
if (RemoteFileExists(ReplaceBookmarksPic))
{
builder.MoveToBookmark(BookmarksName);
builder.InsertImage(ReplaceBookmarksPic, RelativeHorizontalPosition.Page, picLeft, RelativeVerticalPosition.TopMargin, 0, picWidth, picHeight, WrapType.None);
}
}

/// <summary>
/// 插入图片(本地图片),传入书签名称和要替换的值及左侧位置及宽和高即可,不用判断文件是否存在。未测试!!!!
/// </summary>
public void ReplaceBookmarksPic3(string BookmarksName, string ReplaceBookmarksPic, double picLeft, double picWidth, double picHeight)
{
if (LocalFileExists(ReplaceBookmarksPic))
{
builder.MoveToBookmark(BookmarksName);
builder.InsertImage(ReplaceBookmarksPic, RelativeHorizontalPosition.Page, picLeft, RelativeVerticalPosition.TopMargin, 0, picWidth, picHeight, WrapType.None);
}
}

/// <summary>
/// 本地文件是否存在验证
/// </summary>
/// <param name="filePath"></param>
/// <returns></returns>
public bool LocalFileExists(string filePath)
{
try
{
if (File.Exists(filePath))
{
return true;
}
else
{
return false;
}
}
catch (Exception)
{
return false;
}
}

/// <summary>
/// 查找替换
/// </summary>
public void ReplaceText(string SearchText, string ReplaceText)
{
ReplaceText = ReplaceText.Replace("\n", "");
ReplaceText = ReplaceText.Replace("\r", "");
doc.Range.Replace(SearchText, ReplaceText, true, true);
}

/// <summary>
/// 设置页眉页脚,考虑内容和格式是否可以分开处理
/// </summary>

public void SetHeaderFooter1(bool headflag, string HeaderFooterText)
{
//设置移动到页面最底下

builder.MoveToDocumentEnd();

//设置页眉高度

Section currentSection = builder.CurrentSection;
Aspose.Words.PageSetup pageSetup = currentSection.PageSetup;
pageSetup.HeaderDistance = 50;

//移动光标至页眉页脚,设置属性

builder.MoveToHeaderFooter(HeaderFooterType.HeaderPrimary);
//builder.MoveToHeaderFooter(HeaderFooterType.HeaderFirst);
builder.Underline = Underline.Single;
// builder.ParagraphFormat.Alignment = ParagraphAlignment.Center;
// Set font properties for header text.
builder.Font.Name = "宋体";
// builder.RowFormat.Alignment = RowAlignment.Center;
builder.Font.Bold = true;
builder.Font.Size = 11;
// Specify header title for the first page.
if (headflag)
{
builder.Write(HeaderFooterText);
}
}

/// <summary>
/// 设置页眉页脚
/// </summary>
/// <param name="headflag"></param>
/// <param name="HeaderFooterText"></param>
public void SetHeaderFooter(bool headflag, string HeaderFooterText)
{
//设置页眉高度
Section currentSection = builder.CurrentSection;
Aspose.Words.PageSetup pageSetup = currentSection.PageSetup;
pageSetup.HeaderDistance = 25;

if (headflag)
{
builder.Write(HeaderFooterText);
}
}

/// <summary>
/// 设置表格
/// </summary>
/// <param name="headflag"></param>
/// <param name="HeaderFooterText"></param>
public void SetTable(bool headflag, string HeaderFooterText)
{
builder.MoveToDocumentEnd();
builder.StartTable();

builder.RowFormat.Alignment = RowAlignment.Center;
builder.CellFormat.Borders.LineStyle = LineStyle.Single;
builder.CellFormat.Borders.Color = Color.Black;
//builder.CellFormat.VerticalAlignment = CellVerticalAlignment.Center;
//builder.ParagraphFormat.Alignment = ParagraphAlignment.Center;
builder.Bold = true;

builder.InsertCell();
builder.CellFormat.Width = 80;
builder.Write("序号");
//builder.CellFormat.VerticalAlignment = CellVerticalAlignment.Center;
//builder.ParagraphFormat.Alignment = ParagraphAlignment.Center;

builder.InsertCell();
builder.CellFormat.Width = 250;
builder.Write("产品名称");
//builder.CellFormat.VerticalAlignment = CellVerticalAlignment.Center;
//builder.ParagraphFormat.Alignment = ParagraphAlignment.Center;

builder.InsertCell();
builder.CellFormat.Width = 110;
builder.Write("品牌");
//builder.CellFormat.VerticalAlignment = CellVerticalAlignment.Center;
//builder.ParagraphFormat.Alignment = ParagraphAlignment.Center;

builder.InsertCell();
builder.CellFormat.Width = 250;
builder.Write("型号");
//builder.CellFormat.VerticalAlignment = CellVerticalAlignment.Center;
//builder.ParagraphFormat.Alignment = ParagraphAlignment.Center;

builder.InsertCell();
builder.CellFormat.Width = 170;
builder.Write("备注");
//builder.CellFormat.VerticalAlignment = CellVerticalAlignment.Center;
//builder.ParagraphFormat.Alignment = ParagraphAlignment.Center;

builder.EndRow();
}

/// <summary>
/// 设置表格信息
/// </summary>
/// <param name="CellWidth"></param> 单元格宽度
/// <param name="CellTitle"></param> 单元格标题
public void InsertTableCell(int CellWidth, string CellTitle)
{
builder.InsertCell();
builder.CellFormat.Width = CellWidth;
builder.Write(CellTitle);
builder.CellFormat.VerticalAlignment = CellVerticalAlignment.Center;
builder.ParagraphFormat.Alignment = ParagraphAlignment.Center;
}

/// <summary>
/// 获取表格信息
/// </summary>
/// <param name=""></param> 单元格宽度
/// <param name=""></param> 单元格标题
public void GetTableCell(int TableIndex, int RowsIndex, int ColumnIndex, int CharacterIndex, string CellText)
{
NodeCollection allTables = doc.GetChildNodes(NodeType.Table, true);
Table table = allTables[3] as Aspose.Words.Tables.Table;//拿到第一个表格
builder.MoveToCell(0, 2, 1, 0);//先跳转到第0个表格,第31行,第1列
//builder.MoveToCell(TableIndex, RowsIndex, ColumnIndex, CharacterIndex);//先跳转到第0个表格,第31行,第1列
builder.Write(CellText);
}

public void SetCellLocation(int count)
{
try
{
NodeCollection allTables = doc.GetChildNodes(NodeType.Table, true);
//拿到第一个表格
int rowIndex = 5;
Table table = null;
for (int i = 0; i < allTables.Count; i++)
{
bool res = false;
if (!res)
{
table = allTables[i] as Aspose.Words.Tables.Table;
for (int z = 0; z < table.Rows.Count; z++)
{
string tempRow = table.Rows[z].Range.Text.Replace("\a", "");
if (tempRow == "")
{
//beforeRow = table.Rows[z];//正确配置,待复制的空白行
rowIndex = z;
res = true;
break;
}
}
}
}
if (count > 0 && table != null)
{
int colCount = table.Rows[rowIndex + count - 1].Cells.Count;
if (colCount > 0)
{
for (int n = 0; n < colCount; n++)
{
Cell cell = table.Rows[rowIndex + count - 1].Cells[n];

cell.CellFormat.TopPadding = 50;
}
}
}
}
catch (Exception ex)
{
return;
}
}

public void SetCellBackColor(int count)
{
try
{
NodeCollection allTables = doc.GetChildNodes(NodeType.Table, true);
//拿到第一个表格
int rowIndex = 5;
Table table = null;
for (int i = 0; i < allTables.Count; i++)
{
bool res = false;
if (!res)
{
table = allTables[i] as Aspose.Words.Tables.Table;
for (int z = 0; z < table.Rows.Count; z++)
{
string tempRow = table.Rows[z].Range.Text.Replace("\a", "");
if (tempRow == "")
{
//beforeRow = table.Rows[z];//正确配置,待复制的空白行
rowIndex = z;
res = true;
break;
}
}
}
}
if (count > 0 && table != null)
{
for (int m = 1; m <= count; m++)
{
if (m % 2 != 0)
{
int colCount = table.Rows[rowIndex + m].Cells.Count;
if (colCount > 0)
{
for (int n = 0; n < colCount; n++)
{
Cell cell = table.Rows[rowIndex + m].Cells[n];
cell.CellFormat.Shading.BackgroundPatternColor = Color.FromArgb(244, 247, 251);
}
}
}
}
}
}
catch (Exception ex)
{
return;
}
}

public void SetCellMerge(int count)
{
try
{
NodeCollection allTables = doc.GetChildNodes(NodeType.Table, true);
Table table = allTables[0] as Aspose.Words.Tables.Table;//拿到第一个表格
int rowIndex = 5;
if (table != null && table.Rows.Count > 0)
{
for (int z = 0; z < table.Rows.Count; z++)
{
string tempRow = table.Rows[z].Range.Text.Replace("\a", "");
if (tempRow == "")
{
//beforeRow = table.Rows[z];//正确配置,待复制的空白行
rowIndex = z;
break;
}
}
}

if (count >= 2)
{
Cell cell0 = table.Rows[rowIndex + 1].Cells[0];
Cell cell01 = table.Rows[rowIndex + 2].Cells[0];
//单元格内容
string cellContent0 = cell0.GetText().Replace("\a", "");
string cellContent01 = cell01.GetText().Replace("\a", "");
if (cellContent0 == cellContent01)
{
cell0.CellFormat.VerticalMerge = Aspose.Words.Tables.CellMerge.First;
cell01.CellFormat.VerticalMerge = Aspose.Words.Tables.CellMerge.Previous;
if (count == 3)
{
Cell cell02 = table.Rows[rowIndex + 3].Cells[0];
string cellContent02 = cell02.GetText().Replace("\a", "");
if (cellContent01 == cellContent02)
{
cell02.CellFormat.VerticalMerge = Aspose.Words.Tables.CellMerge.Previous;
}
}
}

Cell cell1 = table.Rows[rowIndex + 1].Cells[1];
Cell cell11 = table.Rows[rowIndex + 2].Cells[1];
string cellContent1 = cell1.GetText().Replace("\a", "");
string cellContent11 = cell11.GetText().Replace("\a", "");
if (cellContent1 == cellContent11)
{
cell1.CellFormat.VerticalMerge = Aspose.Words.Tables.CellMerge.First;
cell11.CellFormat.VerticalMerge = Aspose.Words.Tables.CellMerge.Previous;
if (count == 3)
{
Cell cell12 = table.Rows[rowIndex + 3].Cells[1];
string cellContent12 = cell12.GetText().Replace("\a", "");
if (cellContent11 == cellContent12)
{
cell12.CellFormat.VerticalMerge = Aspose.Words.Tables.CellMerge.Previous;
}
}
}

Cell cell40 = table.Rows[rowIndex - 1].Cells[4];
Cell cell4 = table.Rows[rowIndex + 1].Cells[4];
Cell cell41 = table.Rows[rowIndex + 2].Cells[4];
string cellContent40 = cell40.GetText().Replace("\a", "");
string cellContent4 = cell4.GetText().Replace("\a", "");
string cellContent41 = cell41.GetText().Replace("\a", "");
if (cellContent4 == cellContent41 && cellContent40.Contains("检出限"))
{
cell4.CellFormat.VerticalMerge = Aspose.Words.Tables.CellMerge.First;
cell41.CellFormat.VerticalMerge = Aspose.Words.Tables.CellMerge.Previous;
if (count == 3)
{
Cell cell42 = table.Rows[rowIndex + 3].Cells[4];
string cellContent42 = cell42.GetText().Replace("\a", "");
if (cellContent41 == cellContent42)
{
cell42.CellFormat.VerticalMerge = Aspose.Words.Tables.CellMerge.Previous;
}
}
}
}
}
catch (Exception)
{
return;
}
}

/// <summary>
/// 修改表中的数据
/// </summary>
/// <param name="table">表名</param>
/// <param name="doc">文档</param>
/// <param name="row">要修改行</param>
/// <param name="cell">要修改列</param>
/// <param name="value">修改后的值</param>
public Table EditCell(Table table, Document doc, int row, int cell, string value)
{
try
{
//st = cy.FirstParagraph.ParagraphFormat.Style.Font;
Cell c = table.Rows[row].Cells[cell];
Paragraph p = new Paragraph(doc);
p.AppendChild(new Run(doc, value));
p.ParagraphFormat.Alignment = ParagraphAlignment.Center;
//p.ParagraphFormat.Style.Font.Size = 12;
c.FirstParagraph.Remove();
c.AppendChild(p);
table.Rows[row].Cells[cell].Remove();
table.Rows[row].Cells.Insert(cell, c);
}
catch (Exception ex)
{
throw ex;
}
return table;
}

/// <summary>
/// 修改表中的数据(带字体大小,获取列头的字体)
/// </summary>
/// <param name="table">表名</param>
/// <param name="doc">文档</param>
/// <param name="row">要修改行</param>
/// <param name="cell">要修改列</param>
/// <param name="value">修改后的值</param
/// <param name="ft">替换的字体</param>
public Table EditCell(Table table, Document doc, int row, int cell, string value, Aspose.Words.Font ft)
{
try
{
Cell c = table.Rows[row].Cells[cell];
Paragraph p = new Paragraph(doc);
p.AppendChild(new Run(doc, value));
p.ParagraphFormat.Alignment = ParagraphAlignment.Center;
p.ParagraphFormat.Style.Font.Size = ft.Size;
c.FirstParagraph.Remove();
c.AppendChild(p);
table.Rows[row].Cells[cell].Remove();
table.Rows[row].Cells.Insert(cell, c);
}
catch (Exception ex)
{
throw ex;
}
return table;
}

//private string oldValue = "";

/// <summary>
/// 修改表中的数据(带字体大小,获取列头的字体)
/// </summary>
/// <param name="table">表名</param>
/// <param name="doc">文档</param>
/// <param name="row">要修改行</param>
/// <param name="cell">要修改列</param>
/// <param name="value">修改后的值</param
/// <param name="ft">替换的字体</param>
public Table EditCell(Table table, Document doc, int row, int cell, string value, Aspose.Words.Font ft, int x, ref string oldValue)
{
try
{
Cell c = table.Rows[row].Cells[cell];
Paragraph p = new Paragraph(doc);
Run r = null;

if (x == 0)
{
if (cell == 0)
{
oldValue = value;
c.CellFormat.VerticalMerge = Aspose.Words.Tables.CellMerge.First;
c.CellFormat.VerticalAlignment = CellVerticalAlignment.Center;
r = new Run(doc, oldValue);
r.Font.Size = ft.Size;
//p.AppendChild(new Run(doc, oldValue));
p.ParagraphFormat.Alignment = ParagraphAlignment.Center;
//p.ParagraphFormat.Style.Font.Size = ft.Size;
p.AppendChild(r);
}
else
{
c.CellFormat.VerticalMerge = Aspose.Words.Tables.CellMerge.None;
c.CellFormat.VerticalAlignment = CellVerticalAlignment.Center;
r = new Run(doc, value);
r.Font.Size = ft.Size;
//p.AppendChild(new Run(doc, value));
p.ParagraphFormat.Alignment = ParagraphAlignment.Center;
//p.ParagraphFormat.Style.Font.Size = ft.Size;
p.AppendChild(r);
}
}
else
{
if (cell == 0)
{
if (oldValue == value)
{
c.CellFormat.VerticalMerge = Aspose.Words.Tables.CellMerge.Previous;
c.CellFormat.VerticalAlignment = CellVerticalAlignment.Center;
}
else
{
oldValue = value;
c.CellFormat.VerticalMerge = Aspose.Words.Tables.CellMerge.First;
c.CellFormat.VerticalAlignment = CellVerticalAlignment.Center;
//p.AppendChild(new Run(doc, oldValue));
r = new Run(doc, oldValue);
r.Font.Size = ft.Size;
p.ParagraphFormat.Alignment = ParagraphAlignment.Center;
//p.ParagraphFormat.Style.Font.Size = ft.Size;
p.AppendChild(r);
}
}
else
{
//oldValue = value;
c.CellFormat.VerticalMerge = Aspose.Words.Tables.CellMerge.None;
c.CellFormat.VerticalAlignment = CellVerticalAlignment.Center;
//p.AppendChild(new Run(doc, value));
r = new Run(doc, value);
r.Font.Size = ft.Size;
p.ParagraphFormat.Alignment = ParagraphAlignment.Center;
//p.ParagraphFormat.Style.Font.Size = ft.Size;
p.AppendChild(r);
}
}

//if (x == 0)
//{
// p.AppendChild(new Run(doc, value));
// p.ParagraphFormat.Alignment = ParagraphAlignment.Center;
// if (cell == 4|| cell == 0)
// {
// c.CellFormat.VerticalMerge = Aspose.Words.Tables.CellMerge.First;
// c.CellFormat.VerticalAlignment = CellVerticalAlignment.Center;
// }
// else
// {
// c.CellFormat.VerticalMerge = Aspose.Words.Tables.CellMerge.None;
// }
//}
//else
//{
// if (cell == 4 || cell == 0)
// {
// c.CellFormat.VerticalMerge = Aspose.Words.Tables.CellMerge.Previous;
// c.CellFormat.VerticalAlignment = CellVerticalAlignment.Center;
// }
// else
// {
// c.CellFormat.VerticalMerge = Aspose.Words.Tables.CellMerge.None;
// }
//}
c.FirstParagraph.Remove();
c.AppendChild(p);
table.Rows[row].Cells[cell].Remove();
table.Rows[row].Cells.Insert(cell, c);
}
catch (Exception ex)
{
throw ex;
}
return table;
}

public Table EditCell(Table table, Document doc, int row, int cell, string value, double ft, int x, ref string oldValue)
{
try
{
Cell c = table.Rows[row].Cells[cell];
Paragraph p = new Paragraph(doc);

if (x == 0)
{
if (cell == 0)
{
oldValue = value;
c.CellFormat.VerticalMerge = Aspose.Words.Tables.CellMerge.First;
c.CellFormat.VerticalAlignment = CellVerticalAlignment.Center;
p.AppendChild(new Run(doc, oldValue));
p.ParagraphFormat.Alignment = ParagraphAlignment.Center;
//p.ParagraphFormat.Style.Font.Size = ft;
}
else
{
c.CellFormat.VerticalMerge = Aspose.Words.Tables.CellMerge.None;
c.CellFormat.VerticalAlignment = CellVerticalAlignment.Center;
p.AppendChild(new Run(doc, value));
p.ParagraphFormat.Alignment = ParagraphAlignment.Center;
//p.ParagraphFormat.Style.Font.Size = ft;
}
}
else
{
if (cell == 0)
{
if (oldValue == value)
{
c.CellFormat.VerticalMerge = Aspose.Words.Tables.CellMerge.Previous;
c.CellFormat.VerticalAlignment = CellVerticalAlignment.Center;
}
else
{
oldValue = value;
c.CellFormat.VerticalMerge = Aspose.Words.Tables.CellMerge.First;
c.CellFormat.VerticalAlignment = CellVerticalAlignment.Center;
p.AppendChild(new Run(doc, oldValue));
p.ParagraphFormat.Alignment = ParagraphAlignment.Center;
//p.ParagraphFormat.Style.Font.Size = ft;
}
}
else
{
//oldValue = value;
c.CellFormat.VerticalMerge = Aspose.Words.Tables.CellMerge.None;
c.CellFormat.VerticalAlignment = CellVerticalAlignment.Center;
p.AppendChild(new Run(doc, value));
p.ParagraphFormat.Alignment = ParagraphAlignment.Center;
//p.ParagraphFormat.Style.Font.Size = ft;
}
}

//if (x == 0)
//{
// p.AppendChild(new Run(doc, value));
// p.ParagraphFormat.Alignment = ParagraphAlignment.Center;
// if (cell == 4|| cell == 0)
// {
// c.CellFormat.VerticalMerge = Aspose.Words.Tables.CellMerge.First;
// c.CellFormat.VerticalAlignment = CellVerticalAlignment.Center;
// }
// else
// {
// c.CellFormat.VerticalMerge = Aspose.Words.Tables.CellMerge.None;
// }
//}
//else
//{
// if (cell == 4 || cell == 0)
// {
// c.CellFormat.VerticalMerge = Aspose.Words.Tables.CellMerge.Previous;
// c.CellFormat.VerticalAlignment = CellVerticalAlignment.Center;
// }
// else
// {
// c.CellFormat.VerticalMerge = Aspose.Words.Tables.CellMerge.None;
// }
//}
c.FirstParagraph.Remove();
c.AppendChild(p);
table.Rows[row].Cells[cell].Remove();
table.Rows[row].Cells.Insert(cell, c);
}
catch (Exception ex)
{
throw ex;
}
return table;
}

/// <summary>
/// 处理上下标
/// </summary>
/// <param name="table"></param>
/// <param name="doc"></param>
/// <param name="row"></param>
/// <param name="cell"></param>
/// <param name="value"></param>
/// <param name="ft"></param>
/// <param name="x"></param>
/// <param name="oldValue"></param>
/// <returns></returns>
public Table EditLimsCell(Table table, Document doc, int row, int cell, string value, Aspose.Words.Font ft, int x, ref string oldValue)
{
try
{
List<FontSubscript> listFont = new List<FontSubscript>();
Cell c = table.Rows[row].Cells[cell];
Paragraph p = new Paragraph(doc);
Run r = null;

if (x == 0)
{
if (cell == 0)
{
oldValue = value;
c.CellFormat.VerticalMerge = Aspose.Words.Tables.CellMerge.First;
c.CellFormat.VerticalAlignment = CellVerticalAlignment.Center;
listFont = GetFontInfoList(value);
//Dictionary<string, string> dicList = new Dictionary<string, string>();
//dicList.Add("{(.*?)}", "{{{0}}}");

//foreach (var dic in dicList)
//{
// MatchCollection mc = Regex.Matches(oldValue, dic.Key);
// if (mc != null && mc.Count > 0)
// {
// //List<FieldInfo> listF = new List<FieldInfo>();
// //foreach (Match item in mc)
// //{
// // if (!list.Exists(o => o.FieldName == item.Groups[1].Value))
// // {
// // fieldInfo = new FieldInfo();
// // fieldInfo.Type = "文本";
// // fieldInfo.TextReplaceStr = dic.Value;
// // fieldInfo.FieldName = item.Groups[1].Value;
// // list.Add(fieldInfo);
// // }
// //}
// }
//}

//foreach (KeyValuePair<string, string> kvp in dicList)
//{
// Regex regex = new Regex(kvp.Value, RegexOptions.IgnoreCase);
// wh.doc.Range.Replace(regex, new ReplaceEvaluatorFindAndHighlight(), false);
//}
r = new Run(doc, oldValue);
r.Font.Size = ft.Size;
//p.AppendChild(new Run(doc, oldValue));
p.ParagraphFormat.Alignment = ParagraphAlignment.Center;
//p.ParagraphFormat.Style.Font.Size = ft.Size;
p.AppendChild(r);

HandleFontSubscript(listFont, p);
}
else
{
c.CellFormat.VerticalMerge = Aspose.Words.Tables.CellMerge.None;
c.CellFormat.VerticalAlignment = CellVerticalAlignment.Center;

Dictionary<string, string> dicList = new Dictionary<string, string>();
dicList.Add("{(.*?)}", "{{{0}}}");
//dicList.Add("{(.)}", "{{{0}}}");
//dicList.Add("\\[(.*?)\\]", "\\[{0}\\]");
dicList.Add("\\[(.)\\]", "\\[{0}\\]");
//dicList.Add("<sub>(.*?)</sub>", "<sub>{0}</sub>");
//dicList.Add("<sup>(.*?)</sup>", "<sup>{0}</sup>");
//string[] arr = new string[] {"{2}", "{23}"};
//List<string> list = new List<string>();
listFont = GetFontInfoList(value);

#region 注释

//List<FontSubscript> listFont = new List<FontSubscript>();
//Dictionary<int, string> dicT = new Dictionary<int, string>();
//foreach (var dic in dicList)
//{
// MatchCollection mc = Regex.Matches(value, dic.Key);
// if (mc != null && mc.Count > 0)
// {
// FontSubscript ety;
// for (int i = 0; i < mc.Count; i++)
// {
// ety = new FontSubscript();
// if (mc[i].Value.Contains("]") && mc[i].Value.Contains("["))
// {
// ety.FontType = 1;//下标
// //ety.ReplaceText = mc[i].Value.Replace("[", "");
// ety.ReplaceText = "\\[" + mc[i].Groups[1].Value + "\\]";
// ety.ReplaceValue = mc[i].Groups[1].Value;
// listFont.Add(ety);
// }
// if (mc[i].Value.Contains("}") && mc[i].Value.Contains("{"))
// {
// ety.FontType = 0;//上标
// //ety.ReplaceText = mc[i].Value.Replace("}", "");
// ety.ReplaceText = "\\{" + mc[i].Groups[1].Value + "\\}";
// ety.ReplaceValue = mc[i].Groups[1].Value;
// listFont.Add(ety);
// }
// }
// }
//}

#endregion 注释

r = new Run(doc, value);
r.Font.Size = ft.Size;
//p.AppendChild(new Run(doc, value));
p.ParagraphFormat.Alignment = ParagraphAlignment.Center;
//p.ParagraphFormat.Style.Font.Size = ft.Size;
p.AppendChild(r);

HandleFontSubscript(listFont, p);

//if (listFont != null && listFont.Count > 0)
//{
// foreach (var st in listFont)
// {
// Regex regex = new Regex(st.ReplaceText, RegexOptions.IgnoreCase);
// p.Range.Replace(regex, new ReplaceEvaluatorFindAndHighlight(st.FontType), false);
// }
//}
}
}
else
{
if (cell == 0)
{
if (oldValue == value)
{
c.CellFormat.VerticalMerge = Aspose.Words.Tables.CellMerge.Previous;
c.CellFormat.VerticalAlignment = CellVerticalAlignment.Center;
}
else
{
oldValue = value;
c.CellFormat.VerticalMerge = Aspose.Words.Tables.CellMerge.First;
c.CellFormat.VerticalAlignment = CellVerticalAlignment.Center;
listFont = GetFontInfoList(value);
//p.AppendChild(new Run(doc, oldValue));
r = new Run(doc, oldValue);
r.Font.Size = ft.Size;
p.ParagraphFormat.Alignment = ParagraphAlignment.Center;
//p.ParagraphFormat.Style.Font.Size = ft.Size;
p.AppendChild(r);

HandleFontSubscript(listFont, p);
}
}
else
{
//oldValue = value;
c.CellFormat.VerticalMerge = Aspose.Words.Tables.CellMerge.None;
c.CellFormat.VerticalAlignment = CellVerticalAlignment.Center;
listFont = GetFontInfoList(value);
//p.AppendChild(new Run(doc, value));
r = new Run(doc, value);
r.Font.Size = ft.Size;
p.ParagraphFormat.Alignment = ParagraphAlignment.Center;
//p.ParagraphFormat.Style.Font.Size = ft.Size;
p.AppendChild(r);

HandleFontSubscript(listFont, p);
}
}
c.FirstParagraph.Remove();
c.AppendChild(p);
table.Rows[row].Cells[cell].Remove();
table.Rows[row].Cells.Insert(cell, c);
}
catch (Exception ex)
{
throw ex;
}
return table;
}

/// <summary>
/// 获取拆分上下标的字符串
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public List<FontSubscript> GetFontInfoList(string str)
{
List<FontSubscript> list = new List<FontSubscript>();
//str = str + "{-3 }";
if (!string.IsNullOrEmpty(str))
{
Dictionary<string, string> dicList = new Dictionary<string, string>();
dicList.Add("{(.*?)}", "{{{0}}}");
//dicList.Add("{(.)}", "{{{0}}}");
//dicList.Add("\\[(.*?)\\]", "\\[{0}\\]");
dicList.Add("\\[(.*?)\\]", "\\[{0}\\]");
//dicList.Add("\\[(.)\\]", "\\[{0}\\]");
//dicList.Add("<sub>(.*?)</sub>", "<sub>{0}</sub>");
//dicList.Add("<sup>(.*?)</sup>", "<sup>{0}</sup>");
//string[] arr = new string[] {"{2}", "{23}"};
//List<string> list = new List<string>();
//List<FontSubscript> listFont = new List<FontSubscript>();
foreach (var dic in dicList)
{
MatchCollection mc = Regex.Matches(str, dic.Key);
if (mc != null && mc.Count > 0)
{
FontSubscript ety;
for (int i = 0; i < mc.Count; i++)
{
ety = new FontSubscript();
if (mc[i].Value.Contains("]") && mc[i].Value.Contains("["))
{
ety.FontType = 1;//下标
//ety.ReplaceText = mc[i].Value.Replace("[", "");
ety.ReplaceText = "\\[" + mc[i].Groups[1].Value + "\\]";
ety.ReplaceValue = mc[i].Groups[1].Value;
list.Add(ety);
}
if (mc[i].Value.Contains("}") && mc[i].Value.Contains("{"))
{
ety.FontType = 0;//上标
//ety.ReplaceText = mc[i].Value.Replace("}", "");
ety.ReplaceText = "\\{" + mc[i].Groups[1].Value + "\\}";
ety.ReplaceValue = mc[i].Groups[1].Value;
list.Add(ety);
}
}
}
}
}
return list;
}

/// <summary>
/// 处理上下标
/// </summary>
/// <param name="list"></param>
/// <param name="p"></param>
public void HandleFontSubscript(List<FontSubscript> list, Paragraph p)
{
if (list != null && list.Count > 0)
{
foreach (var st in list)
{
Regex regex = new Regex(st.ReplaceText, RegexOptions.IgnoreCase);
p.Range.Replace(regex, new ReplaceEvaluatorFindAndHighlight(st.FontType), false);
}
}
}

public void HandleFontSubscript(List<FontSubscript> list, WordHelper wh)
{
if (list != null && list.Count > 0)
{
foreach (var st in list)
{
Regex regex = new Regex(st.ReplaceText, RegexOptions.IgnoreCase);
wh.doc.Range.Replace(regex, new ReplaceEvaluatorFindAndHighlight(st.FontType), false);
}
}
}

//Dictionary<string, string> dicList = new Dictionary<string, string>();
//dicList.Add("{(.*?)}", "{{{0}}}");

//处理文本中某个字符的样式
private class ReplaceEvaluatorFindAndHighlight : IReplacingCallback
{
public int type { get; set; }

public ReplaceEvaluatorFindAndHighlight(int type)//0:上标;1:下标
{
this.type = type;
}

/// <summary>
/// This method is called by the Aspose.Words find and replace engine for each match.
/// This method highlights the match string, even if it spans multiple runs.
/// </summary>
ReplaceAction IReplacingCallback.Replacing(ReplacingArgs e)
{
Node currentNode = e.MatchNode;
if (e.MatchOffset > 0)
currentNode = SplitRun((Run)currentNode, e.MatchOffset);
ArrayList runs = new ArrayList();

int remainingLength = e.Match.Value.Length;
while (
(remainingLength > 0) &&
(currentNode != null) &&
(currentNode.GetText().Length <= remainingLength))
{
runs.Add(currentNode);
remainingLength = remainingLength - currentNode.GetText().Length;

do
{
currentNode = currentNode.NextSibling;
}
while ((currentNode != null) && (currentNode.NodeType != NodeType.Run));
}

// Split the last run that contains the match if there is any text left.
if ((currentNode != null) && (remainingLength > 0))
{
SplitRun((Run)currentNode, remainingLength);
runs.Add(currentNode);
}

// Now highlight all runs in the sequence.
foreach (Run run in runs)
{
//run.Font.HighlightColor = Color.Yellow;
//run.Font.Name = "宋体";
//run.Font.Size = 16;
//run.Text = "100";
////变成上标
string aa = run.Text;

if (this.type == 0)
{
run.Text = run.Text.Replace("{", "").Replace("}", "");
run.Font.Superscript = true;//上标
}
else
{
run.Text = run.Text.Replace("[", "").Replace("]", "");
run.Font.Subscript = true;//下标
//run.Text= run.Text.Replace("$", "[").Replace("&", "]");
}
}
return ReplaceAction.Skip;
}

//private Node SplitRun(Run currentNode, int matchOffset)
//{
// throw new NotImplementedException();
//}
}

private static Run SplitRun(Run run, int position)
{
Run afterRun = (Run)run.Clone(true);
afterRun.Text = run.Text.Substring(position);
run.Text = run.Text.Substring(0, position);
run.ParentNode.InsertAfter(afterRun, run);
return afterRun;
}

public ParagraphCollection WordParagraphs(string fileName)
{
Document doc = new Document(fileName);
if (doc.FirstSection.Body.Paragraphs.Count > 0)
{
return doc.FirstSection.Body.Paragraphs;//word中的所有段落
}
return null;
}

/// <summary>
/// Word导出
/// </summary>
/// <param name="savePath">转换成Pdf的保存路径</param>
/// <param name="wordFileName">转换成文件名字</param>
public void SaveWord(string savePath, string wordFileName)
{
doc.Save(savePath + "\\" + wordFileName + ".docx");
}

/// <summary>
/// Word导出
/// </summary>
/// <param name="fileName">转换成Pdf的保存路径</param>
public void SaveWord(string fileName)
{
doc.Save(fileName);
}

/// <summary>
/// Word转成Pdf
/// </summary>
/// <param name="savePath">转换成Pdf的保存路径</param>
/// <param name="wordFileName">转换成文件名字</param>
public void SaveDocWord(string savePath, string wordFileName)
{
doc.Save(savePath + "\\" + wordFileName + ".doc");
}

/// <summary>
/// 打印Word
/// </summary>
/// <param name="savePath">转换成Pdf的保存路径</param>
/// <param name="wordFileName">转换成文件名字</param>
public void PrintWord()
{
doc.Print();
}

/// <summary>
/// Word转成Pdf
/// </summary>

/// <param name="savePath">转换成Pdf的保存路径</param>
/// <param name="wordFileName">转换成html的文件名字</param>
public void WordToPDF(string savePath, string wordFileName)
{
//DocumentBuilder builder = new DocumentBuilder(doc);
//builder.Writeln("Test Signed PDF.");
//X509Certificate2 cert = new X509Certificate2(System.Windows.Forms.Application.StartupPath + @"\Temp\" + "Ponymedicine.pfx", "Ponymedicine***");

//Aspose.Words.Saving.PdfSaveOptions saveOption = new Aspose.Words.Saving.PdfSaveOptions();
//saveOption.SaveFormat = Aspose.Words.SaveFormat.Pdf;
//PdfEncryptionDetails encryptionDetails = new PdfEncryptionDetails(string.Empty, "Pony1234", PdfEncryptionAlgorithm.RC4_128);
//encryptionDetails.Permissions = PdfPermissions.DisallowAll;
//encryptionDetails.Permissions = PdfPermissions.Printing;
//saveOption.EncryptionDetails = encryptionDetails;

//saveOption.DigitalSignatureDetails = new PdfDigitalSignatureDetails(cert, "Test Signing", "Aspose Office", DateTime.Now);
//doc.Save(savePath + wordFileName + ".pdf", saveOption);
//PDFSign(savePath + wordFileName + ".pdf");
doc.Save(savePath + wordFileName + ".pdf", SaveFormat.Pdf);
}

public void PDFSign(string savePath)
{
using (Aspose.Pdf.Document pdfDocument = new Aspose.Pdf.Document(savePath))
{
using (PdfFileSignature signature = new PdfFileSignature(pdfDocument))
{
PKCS7 pkcs = new PKCS7(System.Windows.Forms.Application.StartupPath + @"\Temp\" + "puni.pfx", "Ponytest"); // Use PKCS7/PKCS7Detached objects
DocMDPSignature docMdpSignature = new DocMDPSignature(pkcs, DocMDPAccessPermissions.FillingInForms);
System.Drawing.Rectangle rect = new System.Drawing.Rectangle(100, 100, 200, 100);
// Set signature appearance
signature.SignatureAppearance = System.Windows.Forms.Application.StartupPath + @"\Temp\" + "123.bmp";
// Create any of the three signature types
signature.Certify(1, "Signature Reason", "Contact", "Location", true, rect, docMdpSignature);
// Save digitally signed PDF file
signature.Save(savePath);
}
}
}

/// <summary>
/// Word转成Pdf
/// </summary>
/// <param name="path">要转换的文档的路径</param>
/// <param name="savePath">转换成Pdf的保存路径</param>
/// <param name="wordFileName">转换成html的文件名字</param>
public void WordToPDFT(string path, string savePath, string wordFileName)
{
Aspose.Words.Document d = new Aspose.Words.Document(path);
doc.Save(savePath + wordFileName + ".pdf", SaveFormat.Pdf);
}

/// <summary>
/// Word转成jpg
/// </summary>
/// <param name="path">要转换的文档的路径</param>
/// <param name="savePath">转换成Pdf的保存路径</param>
/// <param name="wordFileName">转换成html的文件名字</param>
public void WordToJPG(string path, string savePath, string wordFileName)
{
ImageSaveOptions iso = new ImageSaveOptions(SaveFormat.Jpeg);
iso.Resolution = 128;
iso.PrettyFormat = true;
iso.UseAntiAliasing = true;
for (int i = 0; i < doc.PageCount; i++)
{
iso.PageIndex = i;
doc.Save("D:/test/test" + i + ".jpg", iso);
}
}

#region 判断远程文件是否存在

/// <summary>
/// 判断远程文件是否存在
/// </summary>
/// <param name="fileUrl"></param>
/// <returns></returns>
public static bool RemoteFileExists(string fileUrl)
{
HttpWebRequest re = null;
HttpWebResponse res = null;
try
{
re = (HttpWebRequest)WebRequest.Create(fileUrl);
res = (HttpWebResponse)re.GetResponse();
if (res.ContentLength != 0)
{
//MessageBox.Show("文件存在");
return true;
}
}
catch (Exception)
{
//MessageBox.Show("无此文件");
return false;
}
finally
{
if (re != null)
{
re.Abort();//销毁关闭连接
}
if (res != null)
{
res.Close();//销毁关闭响应
}
}
return false;
}

#endregion 判断远程文件是否存在
}

public class FontSubscript
{
public int FontType { get; set; }//上标,还是下标
public string ReplaceText { get; set; }//替换文本
public string ReplaceValue { get; set; }//替换值
}

public class ReplaceAndInsertImage : IReplacingCallback
{
/// <summary>
/// 需要插入的图片路径
/// </summary>
public string url { get; set; }

public ReplaceAndInsertImage(string url)
{
this.url = url;
}

public ReplaceAction Replacing(ReplacingArgs e)
{
//获取当前节点
var node = e.MatchNode;
//获取当前文档
//Document doc = node.Document as Document;
//DocumentBuilder builder = new DocumentBuilder(doc);
////将光标移动到指定节点
//builder.MoveTo(node);
////插入图片
//builder.InsertImage(url);
return ReplaceAction.Replace;
}
}
}

Gallery:画廊,图库,库

Ribbon:一种电脑用户界面,功能区

accordion:(如手风琴般)可折叠的,手风琴

specification:规格文件

latency:延迟

strees:压力,强调;紧张;重要性;重读

elevate:提高,提升,举起

Bouncy:弹性的,充气的,活泼

Asymmetric:非对称

JIT:Just-in-time,动态(即时)编译

AOT:Ahead Of Time,指运行前编译,边运行边编译

Ahead:提前,前面;领先;未来

Rent:租金;撕裂;破裂处;裂口

Cryptography:密码学

Expiration:过期

Reuse:回用,重复使用;再次使用

widget:小工具;部件;小部件

established:已确立的;已获确认的;确定的;著名的

Inflector:变形器;偏转器;反曲器

Pluralize:多元化

Prioritizers:优先权

Provenance:起源

sensitive: 敏感的

Gist:要点,大意,主旨

aid:帮助,协助,助手

Denotes:表示,指示

crash:碰撞,撞击

Consistent:一致性

Reentry:重复的

Reallocate:重新分配

addins:插件,系统附加文件夹

Deprecated:废弃的, 强烈反对;

maintained:维持; 保持;维修; 保养;

evaluate:评价,评估

slice :切片,名片

strict:严格的,严厉的

infinity:无穷,无限

divide:划分,分配

reveal:揭示,显示,展示

Measure:测量,度量;

ellipsis:省略

Unidirectional :单向的

association:联合,协会

cascade:大量;倾泻; 流注;

Present:存在; 目前

Series:系列,连续;接连

related:相关

Directory:目录

Restriction:限制规定

forbidden:被禁止的

Deag & Drop:拖放

scene:现场

Intelli:智能

Intelligent:智能

IntelliSense:智能感知

Contract:合同

Present:目前

purpose:用途

mandatory:强制的,法定的,命令的

Allocation:分配,分摊,定位

Quantum:定量,单元,量子

Budget:预算

Issuer:发行人

Seed:种子; 籽; 起源; 起因; 萌芽; 开端; 种子选手;

contracts:合同

toolchain:工具链

Early:早期的

EAP: (The Early Access Program) 是指提供免费的提前发布的产品构建

Relational:关系型

snippets:片段,小片,零星的东西

quantity:量;数量;大量;数额

Inventory:库存,财产清单,存货

Thumbprint:指纹

Loopback:环回

Interactive:互动的

Duplex:双工; 复式; 全双工

comparand:比较者

Peek:窥视; 偷看;

Seek:寻找; 寻求;

decorator:装饰

Invoke:引用; 唤起;

marshal:整理,使排列

Infinite:无穷大

Established:确立

individual:单个,个人

Encapsulates:封装,简述,概述,压缩

Similar:类似的,相似

Insensitive:不敏感的,麻木不仁

sensitive:敏感的,体贴的,灵敏

Indented:缩进,缩排

Sequence:序列,顺序;次序;

Segmentums:片段,节段

Elapsed:经过时间;流逝;占用时间;消逝;逝去的;

Contra:相反的

Fallback:备用;回退; 退路

Interop:互操作

Slice:片; 部分,切,把…切成(薄)片;

Span:跨度; 范围; 持续时间;

offset:偏移量;开端;出发; 抵消; 弥补; 补偿;

contiguous:相接的; 相邻的;

authority:权威;权力;权;授权;

direct:直接;径直;亲自

Conflict:冲突; 争执;

Solver:求解器;

Interceptor:拦截器

Packet:数据包,分组; 封包;

Intercept:拦截,截取

Divert:使转向;转接;转移注意力;使转移;转移转向;

earlier:早期的

Reason:原因; 理由; 解释;

Phrase:短语; 词组; 成语;

incoming:传入;进来;到来;收入;

Strategy:策略;计策;

Nginx/Win32是运行在一个控制台程序,而非windows服务方式的。

Nginx/Win32可以使用以下开关来管理它:

1
2
3
4
Nginx -s stop   #快速关闭Nginx,可能不保存相关信息,并迅速终止web服务。(快速退出)
Nginx -s quit #平稳关闭Nginx,保存相关信息,有安排的结束web服务。(平滑退出)
Nginx -s reload #因改变了Nginx相关配置,需要重新加载配置而重载。(重新加载配置)
Nginx -s reopen #重新打开日志文件。(重新加载日志)
阅读全文 »

Nginx配置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
server {
listen 10005;
server_name localhost,127.0.0.1;

#charset koi8-r;

#access_log logs/host.access.log main;

location / {
root E:\code\induction\unpackage\dist\build\h5; # 路径,不支持中文
index index.html index.htm;
}

# 重定向 prefix:匹配的字符串
location ^~ /prefix/ {
rewrite ^/prefix/(.*) /$1 break;
proxy_pass https://api.mokahr.com;
}

#error_page 404 /404.html;

# redirect server error pages to the static page /50x.html
#
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}

# proxy the PHP scripts to Apache listening on 127.0.0.1:80
#
#location ~ \.php$ {
# proxy_pass http://127.0.0.1;
#}

# pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
#
#location ~ \.php$ {
# root html;
# fastcgi_pass 127.0.0.1:9000;
# fastcgi_index index.php;
# fastcgi_param SCRIPT_FILENAME /scripts$fastcgi_script_name;
# include fastcgi_params;
#}

# deny access to .htaccess files, if Apache's document root
# concurs with nginx's one
#
#location ~ /\.ht {
# deny all;
#}
}
阅读全文 »

微信截图_20210823180630.png

微信截图_20210823180722.png

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
/// <summary>
/// 自定义 列名显示
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void dgvGroup_CustomColumnDisplayText(object sender, DevExpress.XtraGrid.Views.Base.CustomColumnDisplayTextEventArgs e)
{
if (e.Column.FieldName == "gender" && e.ListSourceRowIndex != DevExpress.XtraGrid.GridControl.InvalidRowHandle)
{
if (e.Value.ToString() == "0")
e.DisplayText = "男";
else if (e.Value.ToString() == "1")
e.DisplayText = "女";
else
e.DisplayText = "未知";
}
}

uni-appmanifest.json->h5->devServer配置:

微信截图_20210823095017.png

代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
"h5": {
"devServer": {
"port": 8080, // 端口
"disableHostCheck": true,
"proxy": {
"/apis": {
"target": "https://api.mokahr.com",
"changeOrigin": true, //是否跨域
"secure": false // 设置支持https
,"pathRewrite": {
"^/apis": ""
}
}
},
"https": true
}
}
阅读全文 »

被观察者 IObservable<string>

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Utils
{
/// <summary>
/// 消息- 被观察者,提供订阅接口
/// </summary>
public class MsgTracker : IObservable<string>
{
public MsgTracker()
{
observers = new List<IObserver<string>>();
}

private List<IObserver<string>> observers;

public IDisposable Subscribe(IObserver<string> observer)
{
if (!observers.Contains(observer))
observers.Add(observer);
return new Unsubscriber(observers, observer);
}

// 用于取消订阅通知的IDisposable对象的实现
private class Unsubscriber : IDisposable
{
private List<IObserver<string>> _observers;
private IObserver<string> _observer;

public Unsubscriber(List<IObserver<string>> observers, IObserver<string> observer)
{
this._observers = observers;
this._observer = observer;
}

public void Dispose()
{
if (_observer != null && _observers.Contains(_observer))
_observers.Remove(_observer);
}
}

public void TrackMsg(string msg)
{
foreach (var observer in observers)
{
if (string.IsNullOrWhiteSpace(msg))
observer.OnError(new MsgUnknownException());
else
observer.OnNext(msg);
}
}
public void EndMsg()
{
foreach (var observer in observers.ToArray())
if (observers.Contains(observer))
observer.OnCompleted();

observers.Clear();
}

}
public class MsgUnknownException : Exception
{
internal MsgUnknownException()
{ }
}
}
阅读全文 »

IIS 安装

下载
urlrewrite2.exe

配置web.config

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<system.webServer>
<rewrite>
<rules>
<rule name="Handle History Mode and custom 404/500" stopProcessing="true">
<match url="(.*)" />
<conditions logicalGrouping="MatchAll">
<add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
<add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
</conditions>
<action type="Rewrite" url="/index.html" />
</rule>
</rules>
</rewrite>
</system.webServer>
</configuration>
阅读全文 »

1
2
3
4
5
// 安装 npm-check-updates
npm install -g npm-check-updates
npm-check-updates // 运行检查
ncu -u // 更新package.json
npm install // 更新包到最新版

示例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
PS E:\code\syxdevcode.github.io> npm install -g npm-check-updates
npm WARN deprecated request@2.88.2: request has been deprecated, see https://github.com/request/request/issues/3142
npm WARN deprecated har-validator@5.1.5: this library is no longer supported
npm WARN deprecated uuid@3.4.0: Please upgrade to version 7 or higher. Older versions may use Math.random() in certain circumstances, which is known to be problematic. See https://v8.dev/blog/math-random for details.
C:\Users\ponytest\AppData\Roaming\npm\npm-check-updates -> C:\Users\ponytest\AppData\Roaming\npm\node_modules\npm-check-updates\bin\cli.js
C:\Users\ponytest\AppData\Roaming\npm\ncu -> C:\Users\ponytest\AppData\Roaming\npm\node_modules\npm-check-updates\bin\cli.js
+ npm-check-updates@11.8.3
added 311 packages from 167 contributors in 641.613s
[====================] 13/13 100%
PS E:\code\syxdevcode.github.io> npm-check-updates
hexo ^5.3.0 → ^5.4.0 n
hexo-cli ^4.2.0 → ^4.3.0
hexo-deployer-git ^2.1.0 → ^3.0.0
hexo-generator-index ^1.0.0 → ^2.0.0
hexo-generator-searchdb ^1.3.3 → ^1.3.4
hexo-renderer-marked ^2.0.0 → ^4.1.0
hexo-renderer-stylus ^1.1.0 → ^2.0.1
hexo-server ^1.0.0 → ^2.0.0

Run ncu -u to upgrade package.json
PS E:\code\syxdevcode.github.io> ncu -u
[====================] 13/13 100%

hexo ^5.3.0 → ^5.4.0
hexo-cli ^4.2.0 → ^4.3.0
hexo-deployer-git ^2.1.0 → ^3.0.0
hexo-generator-index ^1.0.0 → ^2.0.0
hexo-generator-searchdb ^1.3.3 → ^1.3.4
hexo-renderer-marked ^2.0.0 → ^4.1.0
hexo-renderer-stylus ^1.1.0 → ^2.0.1
hexo-server ^1.0.0 → ^2.0.0

Run npm install to install new versions.

PS E:\code\syxdevcode.github.io> npm install
npm WARN deprecated urix@0.1.0: Please see https://github.com/lydell/urix#deprecated
npm WARN deprecated resolve-url@0.2.1: https://github.com/lydell/resolve-url#deprecated
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@2.3.2 (node_modules\fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@2.3.2: wanted {"os":"darwin","arch":"any"} (current: {"os":"win32","arch":"x64"})
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: nice-napi@1.0.2 (node_modules\nice-napi):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for nice-napi@1.0.2: wanted {"os":"!win32","arch":"any"} (current: {"os":"win32","arch":"x64"})

added 3 packages from 3 contributors, removed 52 packages, updated 10 packages and audited 287 packages in 13.589s

22 packages are looking for funding
run `npm fund` for details

found 0 vulnerabilities

参考:

nodejs包高效升级插件npm-check-updates

一个数组中只有一个数是唯一的,其他数都是成对出现,找出这个唯一的数

使用异或运算

时间复杂度为o(n),空间复杂度为o(1)

两个操作数的位中,相同则结果为0,不同则结果为1。

一个数和0异或还是自己,一个数和自己异或是0。

分析:由于位运算符异或运算的特点,即两个相同的数进行异或运算时,其结果为0,所以当将数组中所有的元素进行异或运算时,其结果必定为那个唯一的数。

1
2
3
4
5
6
7
8
9
static void FindNumber(int[] array)
{
int v = 0;
for (int i = 0; i < array.Length; i++)
{
v ^= array[i];
}
Console.WriteLine("只出现一次的数是:" + v);
}

HashSet方式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
static void FindNumberHashSet(int[] array)
{
HashSet<int> set = new HashSet<int>();
List<int> list = new List<int>();

foreach (var t in array)
{
if(!set.Add(t))
list.Add(t);
}

foreach (var t in set)
{
if(!list.Exists(o => o == t))
Console.WriteLine("只出现一次的数是:" + t);
}
}

一个数组中有两个数是不同的,其他数都是成对出现,找出这两个不同的数

时间复杂度为o(n),空间复杂度为o(1)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
#include <fstream>
#include <iostream>
using namespace std;

int findFirstBit(int num)
{
int firstBit = 0;

while (((num & 1) == 0) && (firstBit < 8 * sizeof(int)))
{
num = num >> 1;
firstBit++;
}
return firstBit;
}

void findTwoDifNums(int arr[], int len, int &num1, int &num2)
{
int sum = 0;
for (int i = 0; i < len; i++)
{
sum ^= arr[i];
}

int firstBit = findFirstBit(sum);

for (int i = 0; i < len; i++)
{
int num = arr[i] >> firstBit;
if (num & 1)
{
num1 ^= arr[i];
}
else
{
num2 ^= arr[i];
}
}
}

int main()
{
int arr2[10] = {2, 3, 4, 9, 6, 4, 3, 9, 2, 8};

int num1 = 0;
int num2 = 0;

findTwoDifNums(arr2, sizeof(arr2) / sizeof(int), num1, num2);

cout << "The different two values is " << num1 << " " << num2 << endl;

getchar();

return 0;
}

参考:
找出数组中唯一不同的数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
public class HttpClientHelper
{
private static string zhongtaiUrl = ConfigurationManager.AppSettings["ZhongTaiUrl"];

/// <summary>
/// 用multipart/form-data发送
/// </summary>
/// <param name="postParaList"></param>
/// <returns></returns>
public static string PostMessage(List<PostDataClass> postParaList)
{
try
{
string responseContent = "";
var memStream = new MemoryStream();
var webRequest = (HttpWebRequest)WebRequest.Create(zhongtaiUrl);
// 边界符
var boundary = "---------------" + DateTime.Now.Ticks.ToString("X");
// 边界符
var beginBoundary = Encoding.ASCII.GetBytes("--" + boundary + "\r\n");
// 最后的结束符
var endBoundary = Encoding.ASCII.GetBytes("--" + boundary + "--\r\n");
memStream.Write(beginBoundary, 0, beginBoundary.Length);
// 设置属性
webRequest.Method = "POST";
webRequest.Timeout = 10000;
webRequest.ContentType = "multipart/form-data; boundary=" + boundary;
for (int i = 0; i < postParaList.Count; i++)
{
PostDataClass temp = postParaList[i];
// 写入字符串的Key
var stringKeyHeader = "Content-Disposition: form-data; name=\"{0}\"" +
"\r\n\r\n{1}\r\n";
var header = string.Format(stringKeyHeader, temp.Prop, temp.Value);
var headerbytes = Encoding.UTF8.GetBytes(header);
memStream.Write(headerbytes, 0, headerbytes.Length);

if (i != postParaList.Count - 1)
memStream.Write(beginBoundary, 0, beginBoundary.Length);
else
// 写入最后的结束边界符
memStream.Write(endBoundary, 0, endBoundary.Length);
}

byte[] b = memStream.ToArray();
string param = System.Text.Encoding.UTF8.GetString(b, 0, b.Length);
LogHelper.Info(string.Format("HttpClientHelper ==> PostMessage参数:{0}", param));

webRequest.ContentLength = memStream.Length;
var requestStream = webRequest.GetRequestStream();
memStream.Position = 0;
var tempBuffer = new byte[memStream.Length];
memStream.Read(tempBuffer, 0, tempBuffer.Length);
memStream.Close();
requestStream.Write(tempBuffer, 0, tempBuffer.Length);
requestStream.Close();
using (HttpWebResponse res = (HttpWebResponse)webRequest.GetResponse())
{
using (Stream resStream = res.GetResponseStream())
{
byte[] buffer = new byte[1024];
int read;
while ((read = resStream.Read(buffer, 0, buffer.Length)) > 0)
{
responseContent += Encoding.UTF8.GetString(buffer, 0, read);
}
}
res.Close();
}

LogHelper.Info(string.Format("HttpClientHelper ==> PostMessage返回值:{0}", responseContent));
return responseContent;
}
catch (Exception e)
{
LogHelper.Error(string.Format("HttpClientHelper ==> PostMessage方法======>Message:{0};StackTrace:{1};Source:{2};", e.Message, e.StackTrace, e.Source));
throw;
}
}
}

public class PostDataClass
{
public string Prop { get; set; }
public string Value { get; set; }
}

从文件读取流和向文件写入流,需要用到 C++ 中另一个标准库 fstream

  • ofstream :该数据类型表示输出文件流,用于创建文件并向文件写入信息。
  • ifstream :该数据类型表示输入文件流,用于从文件读取信息。
  • fstream :该数据类型通常表示文件流,且同时具有 ofstreamifstream 两种功能,这意味着它可以创建文件,向文件写入信息,从文件读取信息。
阅读全文 »

C++ 接口是使用抽象类来实现的。

如果类中至少有一个函数被声明为纯虚函数,则这个类就是抽象类纯虚函数是通过在声明中使用 = 0 来指定的,如下所示:

1
2
3
4
5
6
7
8
9
10
class Box
{
public:
// 纯虚函数
virtual double getVolume() = 0;
private:
double length; // 长度
double breadth; // 宽度
double height; // 高度
};

设计抽象类(通常称为 ABC)的目的,是为了给其他类提供一个可以继承的适当的基类。抽象类不能被用于实例化对象,它只能作为接口使用。如果试图实例化一个抽象类的对象,会导致编译错误。

因此,如果一个 ABC 的子类需要被实例化,则必须实现每个虚函数,这也意味着 C++ 支持使用 ABC 声明接口。如果没有在派生类中重写纯虚函数,就尝试实例化该类的对象,会导致编译错误。

可用于实例化对象的类被称为具体类

阅读全文 »

多态:有多个不同的类,都带有同一个名称但具有不同实现的函数,函数的参数甚至可以是相同的。

C++多态意味着调用成员函数时,会根据调用函数的对象的类型来执行不同的函数;

形成多态必须具备三个条件:

  • 1、必须存在继承关系;
  • 2、继承关系必须有同名虚函数(其中虚函数是在基类中使用关键字Virtual声明的函数,在派生类中重新定义基类中定义的虚函数时,会告诉编译器不要静态链接到该函数);
  • 3、存在基类类型的指针或者引用,通过该指针或引用调用虚函数;
阅读全文 »

C++ 允许在同一作用域中的某个函数和运算符指定多个定义,分别称为函数重载运算符重载

重载声明是指一个与之前已经在该作用域内声明过的函数或方法具有相同名称的声明,但是它们的参数列表和定义(实现)不相同。

当调用一个重载函数或重载运算符时,编译器通过把所使用的参数类型与定义中的参数类型进行比较,决定选用最合适的定义。选择最合适的重载函数或重载运算符的过程,称为重载决策

阅读全文 »