ExcelHelper.cs 75 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using System.Configuration;
  5. using System.Data;
  6. using System.Data.OleDb;
  7. using System.Diagnostics;
  8. using System.IO;
  9. using System.Reflection;
  10. using System.Runtime.InteropServices;
  11. using System.Text;
  12. using System.Text.RegularExpressions;
  13. using System.Web;
  14. using System.Web.UI.WebControls;
  15. using System.Xml;
  16. using System.Xml.Serialization;
  17. using System.Xml.Xsl;
  18. using Excel;
  19. using DataTable = System.Data.DataTable;
  20. namespace ExcelReaderWrite
  21. {
  22. public class ExcelHelper : IDisposable
  23. {
  24. [DllImport("User32.dll", CharSet = CharSet.Auto)]
  25. public static extern int GetWindowThreadProcessId(IntPtr hwnd, out int ID);
  26. //////////////// 私有变量 ////////////////////////////////
  27. #region Application m_excelApplication Excel的Application
  28. private Application m_excelApp;
  29. #endregion
  30. #region Workbook m_excelWorkbook Application的工作薄
  31. /// <summary>
  32. /// Application的工作薄
  33. /// </summary>
  34. private Workbook m_excelWorkbook;
  35. #endregion
  36. #region Sheets m_excelSheets 工作薄的工作表
  37. /// <summary>
  38. /// 工作薄的工作表
  39. /// </summary>
  40. private Sheets m_excelSheets;
  41. #endregion
  42. #region Hashtable m_htData 存放DataTable数据表的Hashtable
  43. /// <summary>
  44. /// 存放DataTable数据表的Hashtable
  45. /// </summary>
  46. private Hashtable m_htData;
  47. #endregion
  48. #region Hashtable m_listSheetName 导出多Sheet的Excel时,Sheet名称
  49. /// <summary>
  50. /// 导出多Sheet的Excel时,Sheet名称
  51. /// </summary>
  52. private Hashtable m_listSheetName;
  53. #endregion
  54. #region string m_stplName Excel配置文件的路径
  55. /// <summary>
  56. /// Excel配置文件的路径
  57. /// </summary>
  58. private string m_stplName;
  59. #endregion
  60. #region string m_tempExcelName Excel临时文件的文件名
  61. /// <summary>
  62. /// Excel临时文件的文件名
  63. /// </summary>
  64. private string m_tempExcelName;
  65. #endregion
  66. #region double KillExcelTime 关闭异常Excel进程的时间(常量)
  67. /// <summary>
  68. /// 关闭异常Excel进程的时间(常量)
  69. /// </summary>
  70. private const double KillExcelTime = 10;
  71. #endregion
  72. #region string URL_ExcelAndXml Excel模版和Xml文件在Web.Config的appSettings中的key
  73. /// <summary>
  74. /// Excel模版和Xml文件在Web.Config的appSettings中的key
  75. /// </summary>
  76. private static string URL_ExcelAndXml
  77. {
  78. get { return GetUrl("XmlTempURL"); }
  79. }
  80. #endregion
  81. #region string URL_UploadFile 存放上传文件的文件夹在Web.Config的appSettings中的key
  82. /// <summary>
  83. /// 存放上传文件的文件夹在Web.Config的appSettings中的key
  84. /// </summary>
  85. private static string URL_UploadFile
  86. {
  87. get { return GetUrl("FileFolderName"); }
  88. }
  89. #endregion
  90. #region string URL_TempFile 导出Excel时临时文件的路径在Web.Config的appSettings中的key
  91. /// <summary>
  92. /// 导出Excel时临时文件的路径在Web.Config的appSettings中的key
  93. /// </summary>
  94. public string url_TempFile;
  95. public string URL_TempFile
  96. {
  97. get
  98. {
  99. if (string.IsNullOrEmpty(url_TempFile))
  100. {
  101. string key = "TempFileFolderName";
  102. StringBuilder sb = new StringBuilder();
  103. sb.Append(GetUrl(key));
  104. sb.Append(Guid.NewGuid());
  105. sb.Append(".xls");
  106. url_TempFile = sb.ToString();
  107. if (UseExistExcel)
  108. {
  109. m_tempExcelName = Guid.NewGuid() + ".xls";
  110. }
  111. }
  112. return url_TempFile;
  113. }
  114. }
  115. #endregion
  116. #region string ValidationExpressionFileName 正则表达式资源文件名(常量)
  117. /// <summary>
  118. /// 正则表达式资源文件名(常量)
  119. /// </summary>
  120. private const string ValidationExpressionFileName = "ValidatorExpression";
  121. #endregion
  122. #region string ValidationExpressionErrorChars 正则表达式非法字符集ID(常量)
  123. /// <summary>
  124. /// 正则表达式资源文件名(常量)
  125. /// </summary>
  126. private const string ValidationExpressionErrorChars = "ErrorChars";
  127. #endregion
  128. #region string MessageFileName Message资源文件名(常量)
  129. /// <summary>
  130. /// Message资源文件名(常量)
  131. /// </summary>
  132. private const string MessageFileName = "Message";
  133. #endregion
  134. #region string MessageID MessageID(常量)
  135. /// <summary>
  136. /// MessageID(常量)
  137. /// </summary>
  138. private const string MessageID = "MSA005";
  139. #endregion
  140. #region string ErrorMessage 错误Message
  141. /// <summary>
  142. /// 错误Message
  143. /// </summary>
  144. private string ErrorMessage = string.Empty;
  145. #endregion
  146. private const string TempText = "Text";
  147. //////////////// 公有变量 ////////////////////////////////
  148. #region enum FillType 填写数据的方式
  149. /// <summary>
  150. /// 填写数据的方式
  151. /// </summary>
  152. public enum FillType
  153. {
  154. /// <summary>
  155. /// 直接填充
  156. /// </summary>
  157. Default,
  158. /// <summary>
  159. /// 插入填充
  160. /// </summary>
  161. Insert,
  162. /// <summary>
  163. /// 复制填充
  164. /// </summary>
  165. Copy,
  166. }
  167. #endregion
  168. #region enum SheetType
  169. /// <summary>
  170. /// XML中配置与Sheet关系的类型
  171. /// </summary>
  172. public enum SheetType
  173. {
  174. /// <summary>
  175. /// 一个Sheet共用一个配置
  176. /// </summary>
  177. OneSheetOneConfig,
  178. /// <summary>
  179. /// 所有Sheet用一个配置
  180. /// </summary>
  181. MoreSheetOneConfig,
  182. }
  183. #endregion
  184. #region string[] MacrosName 宏命令的名称
  185. private string[] macrosName;
  186. /// <summary>
  187. /// 宏命令的名称
  188. /// </summary>
  189. public string[] MacrosName
  190. {
  191. get { return macrosName; }
  192. set { macrosName = value; }
  193. }
  194. #endregion
  195. #region bool HiddenColumn 是否隐藏数据表中没有的列
  196. private bool hiddenColumn;
  197. /// <summary>
  198. /// 是否隐藏数据表中没有的列
  199. /// </summary>
  200. public bool HiddenColumn
  201. {
  202. get { return hiddenColumn; }
  203. set { hiddenColumn = value; }
  204. }
  205. #endregion
  206. #region bool UseExistExcel 是否使用已经存在的Excel
  207. private bool useExistExcel;
  208. /// <summary>
  209. /// 是否使用已经存在的Excel
  210. /// </summary>
  211. public bool UseExistExcel
  212. {
  213. get { return useExistExcel; }
  214. set { useExistExcel = value; }
  215. }
  216. #endregion
  217. //////////////// 公有方法 ////////////////////////////////
  218. #region public ExcelHelper 构造函数
  219. /// <summary>
  220. /// 构造函数
  221. /// </summary>
  222. public ExcelHelper()
  223. {
  224. //结束多余Excel进程
  225. KillExcel();
  226. HiddenColumn = false;
  227. UseExistExcel = false;
  228. }
  229. /// <summary>
  230. /// 构造函数
  231. /// </summary>
  232. /// <param name="tplName">导入Excel时用到XML文件名</param>
  233. public ExcelHelper(string tplName)
  234. {
  235. //创建存放DataTable的Hashtable
  236. m_htData = new Hashtable();
  237. //创建存放Sheet名的Hashtable
  238. m_listSheetName = new Hashtable();
  239. //设置配置文件路径
  240. m_stplName = URL_ExcelAndXml + @"\" + tplName + ".xml";
  241. //结束多余Excel进程
  242. KillExcel();
  243. HiddenColumn = false;
  244. UseExistExcel = false;
  245. }
  246. #endregion
  247. #region public void AddData(string, DataTable) 根据数据表的名字把对应的数据表传入Hashtble保存
  248. /// <summary>
  249. /// 根据数据表的名字把对应的数据表传入Hashtble保存
  250. /// </summary>
  251. /// <param name="sName">DataTable的名字</param>
  252. /// <param name="dtData">DataTable</param>
  253. public void AddData(string sName, DataTable dtData)
  254. {
  255. if (m_htData.ContainsKey(sName))
  256. {
  257. m_htData[sName] = dtData;
  258. }
  259. else
  260. {
  261. m_htData.Add(sName, dtData);
  262. }
  263. }
  264. #endregion
  265. #region public void AddRelation(string, string[], string[]) 多个Sheet用同一个配置时,Sheet也数据源的关系
  266. /// <summary>
  267. /// 多个Sheet用同一个配置时,Sheet也数据源的关系
  268. /// </summary>
  269. /// <param name="sheetName">Sheet的名称</param>
  270. /// <param name="fixNames">固定模式的DataTable名称数组</param>
  271. /// <param name="exNames">扩展模式的DataTable名称数组</param>
  272. public void AddRelation(string sheetName, string[] fixNames, string[] exNames)
  273. {
  274. if (m_htData.ContainsKey(sheetName))
  275. {
  276. m_listSheetName[sheetName] = new string[][] { fixNames, exNames };
  277. }
  278. else
  279. {
  280. m_listSheetName.Add(sheetName, new string[][] { fixNames, exNames });
  281. }
  282. }
  283. #endregion
  284. #region public void ExportExcel 向Excel表中导入数据(无模版)
  285. /// <summary>
  286. /// 向Excel表中导入数据(无模版)
  287. /// </summary>
  288. /// <param name="aFileName">提供给客户端的默认文件名</param>
  289. /// <param name="dtData">数据表</param>
  290. public void ExportExcel(string aFileName, DataTable dtData)
  291. {
  292. foreach (DataColumn column in dtData.Columns)
  293. {
  294. column.ColumnName = Regex.Replace(column.ColumnName, @"\(|\)|(|)", string.Empty, RegexOptions.IgnoreCase);
  295. }
  296. if (string.IsNullOrEmpty(aFileName))
  297. {
  298. aFileName = "Excel" + DateTime.Now.ToString("yyMMddHHmmss");
  299. }
  300. DataSet dsData;
  301. if (dtData.DataSet != null)
  302. {
  303. dsData = dtData.DataSet;
  304. }
  305. else
  306. {
  307. dsData = new DataSet();
  308. dsData.Tables.Add(dtData);
  309. }
  310. ResponseToClient(aFileName, GetExcelXMLDoc(dsData, true));
  311. }
  312. /// <summary>
  313. /// 向Excel表中导入数据(无模版)
  314. /// </summary>
  315. /// <param name="aFileName">提供给客户端的默认文件名</param>
  316. /// <param name="dsData">数据集</param>
  317. public void ExportExcel(string aFileName, DataSet dsData)
  318. {
  319. foreach (DataTable dtData in dsData.Tables)
  320. {
  321. foreach (DataColumn column in dtData.Columns)
  322. {
  323. column.ColumnName = Regex.Replace(column.ColumnName, @"\(|\)|(|)", string.Empty, RegexOptions.IgnoreCase);
  324. }
  325. }
  326. if (string.IsNullOrEmpty(aFileName))
  327. {
  328. aFileName = "Excel" + DateTime.Now.ToString("yyMMddHHmmss");
  329. }
  330. ResponseToClient(aFileName, GetExcelXMLDoc(dsData, true));
  331. }
  332. #endregion
  333. #region public void ExportExcel 向Excel表中导入数据(带模版)
  334. /// <summary>
  335. /// 向Excel表中导入数据(带模版)
  336. /// </summary>
  337. /// <param name="aFileName">提供给客户端的默认文件名</param>
  338. public void ExportExcel(string aFileName)
  339. {
  340. ExportExcel(aFileName, FillType.Default);
  341. }
  342. /// <summary>
  343. /// 向Excel表中导入数据(带模版)
  344. /// </summary>
  345. /// <param name="aFileName">提供给客户端的默认文件名</param>
  346. /// <param name="type">写入数据的方式</param>
  347. public void ExportExcel(string aFileName, FillType type)
  348. {
  349. ExportExcel(aFileName, type, SheetType.OneSheetOneConfig);
  350. }
  351. /// <summary>
  352. /// 向Excel表中导入数据(带模版)
  353. /// </summary>
  354. /// <param name="aFileName">提供给客户端的默认文件名</param>
  355. /// <param name="fillType">写入数据的方式</param>
  356. /// <param name="sheetType">读取模版的方式</param>
  357. public void ExportExcel(string aFileName, FillType fillType, SheetType sheetType)
  358. {
  359. //检查Excel临时文件的路径是否存在,不存在自动创建
  360. CreateDirctory(URL_TempFile);
  361. //获取配置文件模版对象
  362. ReportTemplete rt = GetTemplDefObject();
  363. //复制Excel模版到传入的路径
  364. File.Copy(URL_ExcelAndXml + rt.TempleteFile, URL_TempFile, true);
  365. //打开Excel
  366. OpenExcel(URL_TempFile);
  367. //数据填充Excel
  368. try
  369. {
  370. switch (sheetType)
  371. {
  372. //一个sheet用一个配置的导出
  373. case SheetType.OneSheetOneConfig:
  374. if (rt.FixedSection != null)
  375. {
  376. FillFixData(rt);
  377. }
  378. if (rt.ExtendableSection != null)
  379. {
  380. FillExData(rt, fillType);
  381. }
  382. break;
  383. //所有sheet用一个配置的导出
  384. case SheetType.MoreSheetOneConfig:
  385. if (m_listSheetName.Count > 0)
  386. {
  387. FillData(rt, fillType);
  388. }
  389. break;
  390. default:
  391. break;
  392. }
  393. m_excelWorkbook.Save();
  394. }
  395. catch (Exception ex)
  396. {
  397. throw (ex);
  398. }
  399. //关闭Excel并下载
  400. finally
  401. {
  402. Dispose();
  403. }
  404. ResponseToClient(aFileName, URL_TempFile, true);
  405. }
  406. /// <summary>
  407. /// 向Excel表中导入数据(带模版)
  408. /// </summary>
  409. /// <param name="aFileName">提供给客户端的默认文件名</param>
  410. /// <param name="fillType">写入数据的方式</param>
  411. /// <param name="sheetType">读取模版的方式</param>
  412. /// <param name="isDownload">是否下载Excel</param>
  413. public void ExportExcel(string aFileName, FillType fillType, SheetType sheetType, bool isDownload)
  414. {
  415. //检查Excel临时文件的路径是否存在,不存在自动创建
  416. CreateDirctory(URL_TempFile);
  417. //获取配置文件模版对象
  418. ReportTemplete rt = GetTemplDefObject();
  419. //复制Excel模版到传入的路径
  420. if (!UseExistExcel || !File.Exists(URL_TempFile))
  421. {
  422. File.Copy(URL_ExcelAndXml + rt.TempleteFile, URL_TempFile, true);
  423. }
  424. //打开Excel
  425. OpenExcel(URL_TempFile);
  426. //数据填充Excel
  427. try
  428. {
  429. switch (sheetType)
  430. {
  431. //一个sheet用一个配置的导出
  432. case SheetType.OneSheetOneConfig:
  433. if (rt.FixedSection != null)
  434. {
  435. FillFixData(rt);
  436. }
  437. if (rt.ExtendableSection != null)
  438. {
  439. FillExData(rt, fillType);
  440. }
  441. break;
  442. //所有sheet用一个配置的导出
  443. case SheetType.MoreSheetOneConfig:
  444. if (m_listSheetName.Count > 0)
  445. {
  446. FillData(rt, fillType);
  447. }
  448. break;
  449. default:
  450. break;
  451. }
  452. m_excelWorkbook.Save();
  453. }
  454. catch (Exception ex)
  455. {
  456. throw (ex);
  457. }
  458. //关闭Excel并下载
  459. finally
  460. {
  461. Dispose();
  462. }
  463. if (isDownload)
  464. {
  465. ResponseToClient(aFileName, URL_TempFile, true);
  466. }
  467. }
  468. #endregion
  469. #region public DataSet ImportExcel 上传Excel并将数据导入到DataSet数据集中
  470. /// <summary>
  471. /// 上传Excel并将数据导入到DataSet数据集中
  472. /// </summary>
  473. /// <param name="cotrolName">上传文件的Web控件</param>
  474. /// <returns>DataSet数据集</returns>
  475. public DataSet ImportExcel(FileUpload cotrolName)
  476. {
  477. //Web控件中文件的路径
  478. string filePath = cotrolName.PostedFile.FileName.ToLower().Trim();
  479. if (string.IsNullOrEmpty(filePath))
  480. {
  481. return null;
  482. }
  483. //文件扩展名
  484. string fileExtend = filePath.Substring(filePath.LastIndexOf("."));
  485. if (!".xls".Equals(fileExtend) && !".xlsx".Equals(fileExtend))
  486. {
  487. return null;
  488. }
  489. //取得上传前的文件(存在于客户端)的文件或文件夹的名称
  490. string[] names = filePath.Split('\\');
  491. //取得文件名
  492. string name = names[names.Length - 1];
  493. //判断是否有该目录
  494. filePath = URL_UploadFile + "\\" + name;
  495. CreateDirctory(filePath);
  496. //如果存在,删除文件
  497. if (File.Exists(filePath))
  498. {
  499. File.Delete(filePath);
  500. }
  501. // 上传文件
  502. cotrolName.PostedFile.SaveAs(filePath);
  503. //ODBC连接字符串
  504. string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + filePath.Replace("\\", "\\\\") + ";" +
  505. "Extended Properties=Excel 8.0;";
  506. DataSet ds = new DataSet();
  507. //ODBC上传Excel
  508. OleDbConnection conn = new OleDbConnection(strConn);
  509. conn.Open();
  510. try
  511. {
  512. DataTable table = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables,
  513. new object[] { null, null, null, "TABLE" });
  514. foreach (DataRow row in table.Rows)
  515. {
  516. DataTable dt = new DataTable();
  517. //第几个模板名称
  518. string tablename = row["TABLE_Name"].ToString();
  519. string strSQL = string.Format("select * from [{0}]", tablename);
  520. OleDbCommand cmd = new OleDbCommand(strSQL, conn);
  521. OleDbDataAdapter da = new OleDbDataAdapter();
  522. da.SelectCommand = cmd;
  523. try
  524. {
  525. da.Fill(dt);
  526. TrimDataTable(dt);
  527. ds.Tables.Add(dt);
  528. }
  529. catch (Exception)
  530. {
  531. continue;
  532. }
  533. }
  534. }
  535. catch (Exception ex)
  536. {
  537. throw (ex);
  538. }
  539. finally
  540. {
  541. conn.Close();
  542. }
  543. return ds;
  544. }
  545. /// <summary>
  546. /// 上传Excel并将数据导入到DataSet数据集中
  547. /// </summary>
  548. /// <param name="cotrolName">上传文件的Web控件</param>
  549. /// <param name="type">读取模版的方式</param>
  550. /// <param name="list">格式错误的单元格坐标和正则表达式key</param>
  551. /// <returns>DataSet数据集</returns>
  552. public DataSet ImportExcel(FileUpload cotrolName, SheetType type, ref List<string[]> list)
  553. {
  554. //Web控件中文件的路径
  555. string filePath = cotrolName.PostedFile.FileName.ToLower().Trim();
  556. if (string.IsNullOrEmpty(filePath))
  557. {
  558. return null;
  559. }
  560. string fileExtend = filePath.Substring(filePath.LastIndexOf("."));
  561. if (!".xls".Equals(fileExtend))
  562. {
  563. return null;
  564. }
  565. //取得上传前的文件(存在于客户端)的文件或文件夹的名称
  566. string[] names = filePath.Split('\\');
  567. //取得文件名
  568. string name = names[names.Length - 1];
  569. //判断是否有该目录
  570. filePath = URL_UploadFile + "\\" + name;
  571. CreateDirctory(filePath);
  572. //如果存在,删除文件
  573. if (File.Exists(filePath))
  574. {
  575. File.Delete(filePath);
  576. }
  577. // 上传文件
  578. cotrolName.PostedFile.SaveAs(filePath);
  579. //获取配置文件模版对象
  580. ReportTemplete rt = GetTemplDefObject();
  581. //打开Excel
  582. OpenExcel(filePath);
  583. //导入数据到DataSet中
  584. DataSet ds = new DataSet();
  585. try
  586. {
  587. if (rt.FixedSection != null)
  588. {
  589. ReadFixData(rt, ds, type, list);
  590. }
  591. if (rt.ExtendableSection != null)
  592. {
  593. ReadExData(rt, ds, type, list);
  594. }
  595. }
  596. catch (Exception ex)
  597. {
  598. throw (ex);
  599. }
  600. //关闭Excel
  601. finally
  602. {
  603. Dispose();
  604. }
  605. return ds;
  606. }
  607. #endregion
  608. #region public UpdateXmlUrl(string) 更新XML文件名
  609. /// <summary>
  610. /// 更新XML文件名
  611. /// </summary>
  612. /// <param name="tplName">导入Excel时用到XML文件名</param>
  613. public void UpdateXmlUrl(string tplName)
  614. {
  615. //创建存放DataTable的Hashtable
  616. m_htData = new Hashtable();
  617. //创建存放Sheet名的Hashtable
  618. m_listSheetName = new Hashtable();
  619. //设置配置文件路径
  620. m_stplName = URL_ExcelAndXml + @"\" + tplName + ".xml";
  621. }
  622. #endregion
  623. //////////////// 私有方法 ////////////////////////////////
  624. #region public void Dispose() 销毁Excel进程
  625. /// <summary>
  626. /// 销毁Excel进程
  627. /// </summary>
  628. public void Dispose()
  629. {
  630. if (m_excelSheets != null)
  631. {
  632. Marshal.ReleaseComObject(m_excelSheets);
  633. }
  634. if (m_excelWorkbook != null)
  635. {
  636. m_excelWorkbook.Close(false, Type.Missing, Type.Missing);
  637. Marshal.ReleaseComObject(m_excelWorkbook);
  638. }
  639. if (m_excelApp != null)
  640. {
  641. m_excelApp.Quit();
  642. Marshal.ReleaseComObject(m_excelApp);
  643. KillExcel(m_excelApp);
  644. }
  645. }
  646. #endregion
  647. #region private static void KillExcel() Excel进程关闭
  648. /// <summary>
  649. /// Excel进程关闭
  650. /// </summary>
  651. private static void KillExcel()
  652. {
  653. foreach (Process theProc in Process.GetProcessesByName("EXCEL"))
  654. {
  655. try
  656. {
  657. TimeSpan s = DateTime.Now - theProc.StartTime;
  658. if (s.TotalMinutes >= KillExcelTime && theProc.CloseMainWindow() == false)
  659. {
  660. theProc.Kill();
  661. }
  662. }
  663. catch (Exception)
  664. {
  665. continue;
  666. }
  667. }
  668. }
  669. /// <summary>
  670. /// Excel进程关闭
  671. /// </summary>
  672. /// <param name="excel">Excel的Application</param>
  673. private static void KillExcel(_Application excel)
  674. {
  675. try
  676. {
  677. if (excel != null)
  678. {
  679. //得到这个句柄,具体作用是得到这块内存入口
  680. IntPtr hwnd = new IntPtr(excel.Hwnd);
  681. //得到本进程唯一标志key
  682. int key;
  683. GetWindowThreadProcessId(hwnd, out key);
  684. //得到对进程key的引用
  685. Process process = Process.GetProcessById(key);
  686. //关闭进程key
  687. if (process.CloseMainWindow())
  688. {
  689. process.Kill();
  690. }
  691. }
  692. }
  693. catch
  694. {
  695. }
  696. }
  697. #endregion
  698. #region private static string GetUrl(string) 根据appSettings中的key获取文件夹路径
  699. /// <summary>
  700. /// 根据appSettings中的key获取文件夹路径
  701. /// </summary>
  702. /// <param name="appSettingKey">appSettings中文件夹路径的key</param>
  703. /// <returns>文件夹路径</returns>
  704. private static string GetUrl(string appSettingKey)
  705. {
  706. StringBuilder sb = new StringBuilder();
  707. sb.Append(AppDomain.CurrentDomain.BaseDirectory);
  708. sb.Append(ConfigurationManager.AppSettings[appSettingKey]);
  709. sb.Append(@"\");
  710. return sb.ToString();
  711. }
  712. #endregion
  713. #region private static void CreateDirctory(string) 检查文件夹是否存在,不存在就创建对应的文件夹
  714. /// <summary>
  715. /// 检查文件夹是否存在,不存在就创建对应的文件夹
  716. /// </summary>
  717. /// <param name="url">文件夹路径</param>
  718. private static void CreateDirctory(string url)
  719. {
  720. string[] directoryNames = url.Split(new string[] { @"\" }, StringSplitOptions.RemoveEmptyEntries);
  721. StringBuilder directoryName = new StringBuilder();
  722. for (int i = 0; i < directoryNames.Length - 1; i++)
  723. {
  724. directoryName.Append(directoryNames[i]);
  725. if (!Directory.Exists(directoryName.ToString()))
  726. {
  727. Directory.CreateDirectory(directoryName.ToString());
  728. }
  729. directoryName.Append(@"\");
  730. }
  731. }
  732. #endregion
  733. #region private static void TrimDataTable(DataTable) 去除DataTable中所有字符串的前后空格
  734. /// <summary>
  735. /// 去除DataTable中所有字符串的前后空格
  736. /// </summary>
  737. /// <param name="dataTable">DataTable</param>
  738. private static void TrimDataTable(DataTable dataTable)
  739. {
  740. if (dataTable != null)
  741. {
  742. for (int i = 0; i < dataTable.Rows.Count; i++)
  743. {
  744. for (int j = 0; j < dataTable.Columns.Count; j++)
  745. {
  746. if (dataTable.Columns[j].DataType == typeof(string))
  747. {
  748. dataTable.Rows[i][j] = Convert.ToString(dataTable.Rows[i][j]).Trim();
  749. }
  750. }
  751. }
  752. }
  753. }
  754. #endregion
  755. #region private static void DrawTable(_Worksheet, FixedSection, int) 根据XML文件的定义信息,向Excel输出信息
  756. /// <summary>
  757. /// 根据XML文件的定义信息,向Excel输出信息
  758. /// </summary>
  759. /// <param name="objWorkSheet">工作区</param>
  760. /// <param name="objFiexdSection">包含定义信息的对象</param>
  761. /// <param name="iTimes">第几次画</param>
  762. private static void DrawTable(_Worksheet objWorkSheet, FixedSection objFiexdSection, int iTimes)
  763. {
  764. if (objFiexdSection == null || objFiexdSection.UnitCell == null || objFiexdSection.UnitCell.Length == 0)
  765. {
  766. return;
  767. }
  768. Int32 iDistance = GetDistance(objFiexdSection);
  769. // 根据CELL信息画表格
  770. for (int iCellIndex = 0; iCellIndex < objFiexdSection.UnitCell.Length; iCellIndex++)
  771. {
  772. string strStartP = objFiexdSection.UnitCell[iCellIndex].StartPoint;
  773. string strEndP = objFiexdSection.UnitCell[iCellIndex].EndPoint;
  774. int[] iStartP = ExcelFunction.GetExcelFunction().GetPosition(strStartP);
  775. int[] iEndP = ExcelFunction.GetExcelFunction().GetPosition(strEndP);
  776. //限定每张纸打印2个看板标签
  777. string strNewStartP = (ExcelFunction.GetExcelFunction().GetXByNum(iStartP[1])) +
  778. (iStartP[0] + iDistance * iTimes);
  779. string strNewEndP = (ExcelFunction.GetExcelFunction().GetXByNum(iEndP[1])) +
  780. (iEndP[0] + iDistance * iTimes);
  781. // 字体信息
  782. FontInfo objFontInfo = objFiexdSection.UnitCell[iCellIndex].FontInfo;
  783. // 图片信息
  784. ImageInfo objImageInfo = objFiexdSection.UnitCell[iCellIndex].ImageInfo;
  785. //边框
  786. BorderInfo[] objBorder = objFiexdSection.UnitCell[iCellIndex].BorderInfo;
  787. // 合并单元格
  788. ExcelFunction.GetExcelFunction().CellsUnite(objWorkSheet, strNewStartP, strNewEndP);
  789. // 设置为文本类型
  790. ExcelFunction.GetExcelFunction().SetNumberFormat(objWorkSheet, strNewStartP, strNewEndP);
  791. // 对齐方式(水平)
  792. ExcelFunction.GetExcelFunction().CellsHAlignment(objWorkSheet, strNewStartP, strNewEndP,
  793. (ExcelEnum.ExcelHAlign)
  794. Enum.Parse(typeof(ExcelEnum.ExcelHAlign),
  795. objFiexdSection.UnitCell[iCellIndex].HAlign.ToString(),
  796. true));
  797. // 对齐方式(垂直)
  798. ExcelFunction.GetExcelFunction().CellsVAlignment(objWorkSheet, strNewStartP, strNewEndP,
  799. (ExcelEnum.ExcelVAlign)
  800. Enum.Parse(typeof(ExcelEnum.ExcelVAlign),
  801. objFiexdSection.UnitCell[iCellIndex].VAlign.ToString(),
  802. true));
  803. if (objFiexdSection.UnitCell[iCellIndex].IsImage)
  804. {
  805. // 图片
  806. if (objImageInfo == null)
  807. {
  808. continue;
  809. }
  810. else
  811. {
  812. // 插入图片
  813. ExcelFunction.GetExcelFunction().InsertPictures(objWorkSheet,
  814. AppDomain.CurrentDomain.BaseDirectory + "\\Images\\" +
  815. objImageInfo.ImagePath,
  816. strNewStartP, strNewEndP,
  817. Convert.ToSingle(objImageInfo.ImageWidth),
  818. Convert.ToSingle(objImageInfo.ImageHeight),
  819. Convert.ToSingle(objImageInfo.PaddLeftTop));
  820. }
  821. }
  822. if (objFontInfo != null)
  823. {
  824. // 字体信息
  825. ExcelFunction.GetExcelFunction().FontNameSize(objWorkSheet, strNewStartP, strNewEndP, objFontInfo.FontName,
  826. objFontInfo.FontSize, objFiexdSection.UnitCell[iCellIndex].Text);
  827. // 字体显示方向
  828. ExcelFunction.GetExcelFunction().SetValueOrientation(objWorkSheet, strNewStartP, strNewEndP, objFontInfo.Orientation);
  829. // 字体粗体
  830. ExcelFunction.GetExcelFunction().FontStyle(objWorkSheet, strNewStartP, strNewEndP, objFontInfo.IsBold,
  831. objFontInfo.IsItalic);
  832. // 下划线
  833. ExcelFunction.GetExcelFunction().FontStyle(objWorkSheet, strNewStartP, strNewEndP,
  834. (ExcelEnum.UnderlineStyle)
  835. Enum.Parse(typeof(ExcelEnum.UnderlineStyle),
  836. objFontInfo.UnderLine.ToString(), true));
  837. // 字体颜色
  838. ExcelFunction.GetExcelFunction().CellsBackColor(objWorkSheet, strNewStartP, strNewEndP,
  839. (ExcelEnum.ColorIndex)
  840. Enum.Parse(typeof(ExcelEnum.ColorIndex),
  841. objFiexdSection.UnitCell[iCellIndex].BackColor.ToString
  842. (), true));
  843. }
  844. if (objBorder != null && objBorder.Length > 0)
  845. {
  846. // 画边框
  847. for (int iBorderIndex = 0; iBorderIndex < objBorder.Length; iBorderIndex++)
  848. {
  849. ExcelFunction.GetExcelFunction().DrawEdge(objWorkSheet, strNewStartP, strNewEndP,
  850. (XlBordersIndex)
  851. Enum.Parse(typeof(ExcelEnum.Edge),
  852. objBorder[iBorderIndex].BorderEdge.ToString(), true),
  853. objBorder[iBorderIndex].BorderWeight.ToString(),
  854. (ExcelEnum.ColorIndex)
  855. Enum.Parse(typeof(ExcelEnum.ColorIndex),
  856. objBorder[iBorderIndex].BorderColor.ToString(), true),
  857. objBorder[iBorderIndex].LineStype.ToString());
  858. }
  859. }
  860. }
  861. }
  862. #endregion
  863. #region private static string GetExcelXMLDoc(DataSet, bool) 获取Excel文件的XML格式内容
  864. /// <summary>
  865. /// 获取Excel文件的XML格式内容
  866. /// </summary>
  867. /// <param name="dsData">数据集</param>
  868. /// <param name="aIsShowColName">是否需要导出列名</param>
  869. /// <returns>格式化好后的文档字符串</returns>
  870. private static string GetExcelXMLDoc(DataSet dsData, bool aIsShowColName)
  871. {
  872. //装载数据
  873. XmlDocument xmlDoc = new XmlDocument();
  874. xmlDoc.LoadXml(dsData.GetXml());
  875. //追加列名
  876. if (aIsShowColName)
  877. {
  878. XmlNode nodeRoot = xmlDoc.GetElementsByTagName(dsData.DataSetName).Item(0);
  879. foreach (DataTable dtData in dsData.Tables)
  880. {
  881. XmlNode nodeTmp = xmlDoc.GetElementsByTagName(dtData.TableName).Item(0);
  882. XmlNode nodeNew = xmlDoc.CreateNode(XmlNodeType.Element, "列" + dtData.TableName, null);
  883. foreach (DataColumn column in dtData.Columns)
  884. {
  885. nodeNew.InnerXml += string.Format("<{0}>{0}</{0}>", column.ColumnName);
  886. }
  887. nodeRoot.InsertBefore(nodeNew, nodeTmp);
  888. }
  889. }
  890. //样式化数据
  891. #pragma warning disable 618,612
  892. #pragma warning disable 618,612
  893. XslTransform xslt = new XslTransform();
  894. #pragma warning restore 618,612
  895. #pragma warning restore 618,612
  896. xslt.Load(new XmlTextReader(CreateStyleExcel(dsData)), null, null);
  897. StringWriter sw = new StringWriter();
  898. xslt.Transform(xmlDoc.DocumentElement.CreateNavigator(), null, sw);
  899. string sReturn = sw.ToString().Replace(" encoding=\"utf-8\"", string.Empty);
  900. sw.Close();
  901. return sReturn;
  902. }
  903. #endregion
  904. #region private static MemoryStream CreateStyleExcel(DataSet) 根据DataSet创建Excel样式表
  905. /// <summary>
  906. /// 根据DataSet创建Excel样式表。
  907. /// </summary>
  908. /// <param name="aDs">数据源</param>
  909. /// <returns>Excel样式表</returns>
  910. private static MemoryStream CreateStyleExcel(DataSet aDs)
  911. {
  912. StringBuilder sbStyle = new StringBuilder();
  913. sbStyle.Append(@"<?xml version=""1.0""?>
  914. <xsl:stylesheet version=""1.0"" xmlns:xsl=""http://www.w3.org/1999/XSL/Transform"">
  915. <xsl:template match=""/"">
  916. <Workbook
  917. xmlns=""urn:schemas-microsoft-com:office:spreadsheet""
  918. xmlns:o=""urn:schemas-microsoft-com:office:office""
  919. xmlns:x=""urn:schemas-microsoft-com:office:excel""
  920. xmlns:ss=""urn:schemas-microsoft-com:office:spreadsheet""
  921. xmlns:html=""http://www.w3.org/TR/REC-html40"">");
  922. foreach (DataTable dt in aDs.Tables)
  923. {
  924. sbStyle.Append(@"
  925. <Worksheet ss:Name=""" + dt.TableName + @""">
  926. <Table>
  927. <xsl:for-each select=""" + aDs.DataSetName + "/列" + dt.TableName + @""">
  928. <Row>");
  929. foreach (DataColumn column in dt.Columns)
  930. {
  931. sbStyle.Append(@"
  932. <Cell>
  933. <Data ss:Type=""String"">
  934. <xsl:value-of select=""" + column.ColumnName + @"""/>
  935. </Data>
  936. </Cell>");
  937. }
  938. sbStyle.Append(@"
  939. </Row></xsl:for-each><xsl:for-each select=""" + aDs.DataSetName + "/" + dt.TableName + @"""><Row>");
  940. foreach (DataColumn column in dt.Columns)
  941. {
  942. if (column.DataType.IsSubclassOf(Type.GetType("System.ValueType"))
  943. && column.DataType.Name != "DateTime" && column.DataType.Name != "Boolean")
  944. {
  945. sbStyle.Append(@"
  946. <Cell>
  947. <Data ss:Type=""Number"">
  948. <xsl:value-of select=""" + column.ColumnName + @"""/>
  949. </Data>
  950. </Cell>");
  951. }
  952. else
  953. {
  954. sbStyle.Append(@"
  955. <Cell>
  956. <Data ss:Type=""String"">
  957. <xsl:value-of select=""" + column.ColumnName + @"""/>
  958. </Data>
  959. </Cell>");
  960. }
  961. }
  962. sbStyle.Append(@"
  963. </Row>
  964. </xsl:for-each>
  965. </Table>
  966. </Worksheet>");
  967. }
  968. sbStyle.Append(@"
  969. </Workbook>
  970. </xsl:template>
  971. </xsl:stylesheet>");
  972. MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(sbStyle.ToString()));
  973. stream.Seek(0, SeekOrigin.Begin);
  974. return stream;
  975. }
  976. #endregion
  977. #region private static int GetDistance(FixedSection) 得到两个单元格的横坐标差值
  978. /// <summary>
  979. /// 得到两个单元格的横坐标差值
  980. /// </summary>
  981. /// <param name="obj"></param>
  982. /// <returns></returns>
  983. private static int GetDistance(FixedSection obj)
  984. {
  985. string strStartPostion = obj.ReplateStartPostion;
  986. string strEndPostion = obj.ReplateEndPostion;
  987. int iStartPostionX = GetPostionY(strStartPostion);
  988. int iEndPostionX = GetPostionY(strEndPostion);
  989. return iEndPostionX - iStartPostionX + 1;
  990. }
  991. #endregion
  992. #region private static int GetPostionY(string) 得到单元格的纵坐标
  993. /// <summary>
  994. /// 得到单元格的纵坐标
  995. /// </summary>
  996. /// <param name="strPostion">单元格坐标</param>
  997. /// <returns>单元格的纵坐标</returns>
  998. private static int GetPostionY(string strPostion)
  999. {
  1000. char[] chPostion = strPostion.ToCharArray();
  1001. int iIndex;
  1002. for (iIndex = 0; iIndex < chPostion.Length; iIndex++)
  1003. {
  1004. if (chPostion[iIndex] >= '0' && chPostion[iIndex] <= '9')
  1005. {
  1006. break;
  1007. }
  1008. }
  1009. return Convert.ToInt32(strPostion.Substring(iIndex));
  1010. }
  1011. #endregion
  1012. #region private static string GetPostionX(string) 得到单元格的横坐标
  1013. /// <summary>
  1014. /// 得到单元格的横坐标
  1015. /// </summary>
  1016. /// <param name="strPostion">单元格坐标</param>
  1017. /// <returns>单元格的横坐标</returns>
  1018. private static string GetPostionX(string strPostion)
  1019. {
  1020. char[] chPostion = strPostion.ToCharArray();
  1021. int iIndex;
  1022. for (iIndex = 0; iIndex < chPostion.Length; iIndex++)
  1023. {
  1024. if (chPostion[iIndex] >= '0' && chPostion[iIndex] <= '9')
  1025. {
  1026. break;
  1027. }
  1028. }
  1029. return strPostion.Substring(0, iIndex);
  1030. }
  1031. #endregion
  1032. #region private ReportTemplete GetTemplDefObject() 获得定义的模板对象并返回
  1033. /// <summary>
  1034. /// 获得定义的模板对象并返回
  1035. /// </summary>
  1036. /// <returns></returns>
  1037. private ReportTemplete GetTemplDefObject()
  1038. {
  1039. StreamReader sr = new StreamReader(m_stplName);
  1040. ReportTemplete rt;
  1041. try
  1042. {
  1043. XmlSerializer xs = new XmlSerializer(typeof(ReportTemplete));
  1044. rt = (ReportTemplete)xs.Deserialize(sr);
  1045. }
  1046. finally
  1047. {
  1048. sr.Close();
  1049. }
  1050. return rt;
  1051. }
  1052. #endregion
  1053. #region private DataTable GetData(string) 根据名字获得DataTable的值
  1054. /// <summary>
  1055. /// 根据名字获得DataTable的值
  1056. /// </summary>
  1057. /// <param name="sName"></param>
  1058. /// <returns></returns>
  1059. private DataTable GetData(string sName)
  1060. {
  1061. return (DataTable)m_htData[sName];
  1062. }
  1063. #endregion
  1064. #region private bool ValidationString(string, string) 验证字符串格式是否正确
  1065. /// <summary>
  1066. /// 验证字符串格式是否正确
  1067. /// </summary>
  1068. /// <param name="str">需要验证的字符串</param>
  1069. /// <param name="validationExpressionKey">资源文件中正则表达式的key</param>
  1070. /// <returns>返回true表示格式正确,false表示格式错误</returns>
  1071. private static bool ValidationString(string str, string validationExpressionKey)
  1072. {
  1073. if (string.IsNullOrEmpty(validationExpressionKey))
  1074. {
  1075. return true;
  1076. }
  1077. else
  1078. {
  1079. bool IsRight;
  1080. string validationExpressionValue =
  1081. Convert.ToString(HttpContext.GetGlobalResourceObject(ValidationExpressionFileName,
  1082. validationExpressionKey)).Replace(@"\\", @"\");
  1083. Regex regex = new Regex(validationExpressionValue);
  1084. IsRight = regex.IsMatch(str);
  1085. if (validationExpressionKey.Contains(TempText))
  1086. {
  1087. int width = 0;
  1088. char[] chars = str.ToCharArray();
  1089. int maxLenght = Convert.ToInt32(validationExpressionKey.Replace(TempText, string.Empty));
  1090. Regex singleChar = new Regex("^[\x00-\xff]$");
  1091. foreach (char c in chars)
  1092. {
  1093. width++;
  1094. if (!singleChar.IsMatch(Convert.ToString(c)))
  1095. {
  1096. width++;
  1097. }
  1098. }
  1099. if (width > maxLenght)
  1100. {
  1101. IsRight = false;
  1102. }
  1103. }
  1104. return IsRight;
  1105. }
  1106. }
  1107. #endregion
  1108. #region private static bool Contains(List<string[]>, string[]) 确定某string数组在List中是否存在
  1109. /// <summary>
  1110. /// 确定某string数组在List中是否存在
  1111. /// </summary>
  1112. /// <param name="list">List</param>
  1113. /// <param name="stringArray">string数组</param>
  1114. /// <returns>返回true表示存在,false表示不存在</returns>
  1115. private static bool Contains(List<string[]> list, string[] stringArray)
  1116. {
  1117. bool exist = false;
  1118. foreach (string[] str in list)
  1119. {
  1120. if (str.Length == stringArray.Length)
  1121. {
  1122. int sameCount = 0;
  1123. for (int j = 0; j < stringArray.Length; j++)
  1124. {
  1125. if (str[j].Equals(stringArray[j]))
  1126. {
  1127. sameCount++;
  1128. }
  1129. }
  1130. if (sameCount == stringArray.Length)
  1131. {
  1132. exist = true;
  1133. }
  1134. }
  1135. }
  1136. return exist;
  1137. }
  1138. #endregion
  1139. #region private void OpenExcel(string) 打开一个Excel对象
  1140. /// <summary>
  1141. /// 打开一个Excel对象
  1142. /// </summary>
  1143. /// <param name="sReportFileName"></param>
  1144. private void OpenExcel(string sReportFileName)
  1145. {
  1146. m_excelApp = new Application();
  1147. m_excelApp.Visible = false;
  1148. lock (m_excelApp)
  1149. {
  1150. m_excelWorkbook = m_excelApp.Workbooks._Open(sReportFileName, 0, false, 5, string.Empty, string.Empty,
  1151. false, XlPlatform.xlWindows, string.Empty, true, false, 0, true);
  1152. m_excelSheets = m_excelWorkbook.Worksheets;
  1153. }
  1154. }
  1155. #endregion
  1156. #region private void FillFixData(ReportTemplete) 填写固定模式的值
  1157. /// <summary>
  1158. /// 填写固定模式的值
  1159. /// </summary>
  1160. /// <param name="rt"></param>
  1161. private void FillFixData(ReportTemplete rt)
  1162. {
  1163. for (int j = 0; j < rt.FixedSection.Length; j++)
  1164. {
  1165. FixedSection fs = rt.FixedSection[j];
  1166. DataTable datatb = GetData(fs.Name);
  1167. if (datatb == null || datatb.Rows.Count < 1)
  1168. {
  1169. continue;
  1170. }
  1171. //获取工作区
  1172. _Worksheet excelWorksheet = (_Worksheet)m_excelSheets.get_Item(fs.SheetName);
  1173. if (fs.Rotate)
  1174. {
  1175. // 不规则,整体循环打印
  1176. Int32 iDistance = GetDistance(fs);
  1177. // 根据数据来填充模块
  1178. for (int iCount = 0; iCount < datatb.Rows.Count; iCount++)
  1179. {
  1180. DrawTable(excelWorksheet, fs, iCount);
  1181. for (int i = 0; i < fs.Cell.Length; i++)
  1182. {
  1183. Cell c = fs.Cell[i];
  1184. string strPostion = (GetPostionX(c.Position) +
  1185. (GetPostionY(c.Position) + iDistance * iCount));
  1186. Range range =
  1187. excelWorksheet.get_Range(strPostion, Missing.Value);
  1188. string dtvalue = datatb.Rows[iCount][c.DataName].ToString();
  1189. range.Value2 = dtvalue;
  1190. }
  1191. }
  1192. }
  1193. else
  1194. {
  1195. for (int i = 0; i < fs.Cell.Length; i++)
  1196. {
  1197. Cell cell = fs.Cell[i];
  1198. Range range = excelWorksheet.get_Range(cell.Position, Type.Missing);
  1199. string dtValue = datatb.Rows[0][cell.DataName].ToString();
  1200. range.Value2 = dtValue;
  1201. }
  1202. }
  1203. }
  1204. }
  1205. #endregion
  1206. #region private void FillExData(ReportTemplete, FillType) 填写扩展模式的值
  1207. /// <summary>
  1208. /// 填写扩展模式的值
  1209. /// </summary>
  1210. /// <param name="rt"></param>
  1211. /// <param name="type"></param>
  1212. private void FillExData(ReportTemplete rt, FillType type)
  1213. {
  1214. for (int m = 0; m < rt.ExtendableSection.Length; m++)
  1215. {
  1216. //填充数据
  1217. FillExtandableSection(rt.ExtendableSection[m], type);
  1218. //调用宏
  1219. if (MacrosName != null)
  1220. {
  1221. foreach (string macroName in MacrosName)
  1222. {
  1223. Worksheet excelWorksheet =
  1224. (Worksheet)m_excelSheets.get_Item(rt.ExtendableSection[m].SheetName);
  1225. Application runRange = excelWorksheet.Application;
  1226. object missing = Missing.Value;
  1227. runRange.Run(macroName, missing, missing, missing, missing, missing, missing, missing, missing, missing,
  1228. missing, missing, missing, missing, missing, missing, missing, missing, missing, missing,
  1229. missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing);
  1230. }
  1231. }
  1232. }
  1233. if (rt.ExtendableSection.Length > 0)
  1234. {
  1235. ((Worksheet)m_excelSheets.get_Item(rt.ExtendableSection[0].SheetName)).Activate();
  1236. }
  1237. if (!string.IsNullOrEmpty(ErrorMessage))
  1238. {
  1239. throw new EndOfStreamException(ErrorMessage);
  1240. }
  1241. }
  1242. #endregion
  1243. #region private void FillData(ReportTemplete, FillType) 填写值(所有sheet用一个模版)
  1244. /// <summary>
  1245. /// 填写值(所有sheet用一个模版)
  1246. /// </summary>
  1247. /// <param name="rt"></param>
  1248. /// <param name="fillType"></param>
  1249. private void FillData(ReportTemplete rt, FillType fillType)
  1250. {
  1251. int count = m_excelWorkbook.Sheets.Count;
  1252. Worksheet worksheet = (Worksheet)m_excelWorkbook.Sheets[m_excelWorkbook.Sheets.Count];
  1253. for (int m = 1; m < m_listSheetName.Count; m++)
  1254. {
  1255. worksheet.Copy(worksheet, Type.Missing);
  1256. }
  1257. foreach (string key in m_listSheetName.Keys)
  1258. {
  1259. string[][] newNames = (string[][])m_listSheetName[key];
  1260. Worksheet newWorksheet = (Worksheet)m_excelWorkbook.Sheets[count];
  1261. newWorksheet.Name = key;
  1262. for (int m = 0; m < newNames[0].Length; m++)
  1263. {
  1264. rt.FixedSection[m].Name = newNames[0][m];
  1265. rt.FixedSection[m].Describe = key;
  1266. rt.FixedSection[m].SheetName = key;
  1267. }
  1268. for (int m = 0; m < newNames[1].Length; m++)
  1269. {
  1270. rt.ExtendableSection[m].Name = newNames[1][m];
  1271. rt.ExtendableSection[m].Descirbe = key;
  1272. rt.ExtendableSection[m].SheetName = key;
  1273. }
  1274. if (rt.FixedSection != null)
  1275. {
  1276. FillFixData(rt);
  1277. }
  1278. if (rt.ExtendableSection != null)
  1279. {
  1280. FillExData(rt, fillType);
  1281. }
  1282. count++;
  1283. }
  1284. }
  1285. #endregion
  1286. #region private void FillExtandableSection(ExtendableSection, FillType) 填写一个具体数据区的值
  1287. /// <summary>
  1288. /// 填写一个具体数据区的值
  1289. /// </summary>
  1290. /// <param name="es"></param>
  1291. /// <param name="type"></param>
  1292. private void FillExtandableSection(ExtendableSection es, FillType type)
  1293. {
  1294. //获取数据表
  1295. DataTable datatb = GetData(es.Name);
  1296. if (datatb == null || datatb.Rows.Count < 1)
  1297. {
  1298. return;
  1299. }
  1300. if (!string.IsNullOrEmpty(es.DownloadMaxCount)
  1301. && datatb.Rows.Count > Convert.ToInt32(es.DownloadMaxCount))
  1302. {
  1303. string message = Convert.ToString(HttpContext.GetGlobalResourceObject(MessageFileName, MessageID));
  1304. ErrorMessage += es.SheetName
  1305. + ":"
  1306. + string.Format(message, "Download", es.DownloadMaxCount)
  1307. + "\\r\\n";
  1308. return;
  1309. }
  1310. //如果没设置StartPosition属性,初始化为“A1”
  1311. if (string.IsNullOrEmpty(es.Position))
  1312. {
  1313. es.Position = "A1";
  1314. }
  1315. //获取工作区
  1316. Worksheet worksheet = (Worksheet)m_excelSheets.get_Item(es.SheetName);
  1317. worksheet.Activate();
  1318. //获取第一行的纵坐标
  1319. int yPos = ExcelFunction.GetExcelFunction().GetPosition(es.Position)[0];
  1320. //根据数据填写方式添加新行
  1321. Range excelRange;
  1322. if (!es.Rotate)
  1323. {
  1324. switch (type)
  1325. {
  1326. //直接填充,不做添加操作
  1327. case FillType.Default:
  1328. break;
  1329. //插入填充,插入与数据集相同的行
  1330. case FillType.Insert:
  1331. for (int i = 1; i < datatb.Rows.Count; i++)
  1332. {
  1333. yPos++;
  1334. excelRange = (Range)worksheet.Rows[yPos, Type.Missing];
  1335. excelRange.Select();
  1336. excelRange.Insert(XlDirection.xlDown, Type.Missing);
  1337. }
  1338. yPos++;
  1339. excelRange = (Range)worksheet.Rows[yPos, Type.Missing];
  1340. excelRange.Delete(XlDirection.xlDown);
  1341. break;
  1342. //复制填充,复制与数据集相同的行
  1343. case FillType.Copy:
  1344. for (int i = 1; i < datatb.Rows.Count; i++)
  1345. {
  1346. excelRange = (Range)worksheet.Rows[yPos, Type.Missing];
  1347. excelRange.Select();
  1348. excelRange.Copy(Missing.Value);
  1349. yPos++;
  1350. excelRange = (Range)worksheet.Rows[yPos, Type.Missing];
  1351. excelRange.Select();
  1352. excelRange.Insert(XlDirection.xlDown, Type.Missing);
  1353. }
  1354. yPos++;
  1355. excelRange = (Range)worksheet.Rows[yPos, Type.Missing];
  1356. excelRange.Delete(XlDirection.xlUp);
  1357. break;
  1358. default:
  1359. break;
  1360. }
  1361. }
  1362. var intx = 0;
  1363. var inty = 0;
  1364. //循环添加数据
  1365. for (int j = 0; j < es.RowDefine.Length; j++)
  1366. {
  1367. if (HiddenColumn && !datatb.Columns.Contains(es.RowDefine[j].DataName))
  1368. {
  1369. int[] pos;
  1370. if (es.RowDefine[j].Position == null)
  1371. {
  1372. pos = ExcelFunction.GetExcelFunction().GetPosition(es.Position);
  1373. }
  1374. else
  1375. {
  1376. pos = ExcelFunction.GetExcelFunction().GetPosition(es.RowDefine[j].Position);
  1377. }
  1378. Range range = ((Range)worksheet.Columns[pos[1], Type.Missing]);
  1379. range.Select();
  1380. range.EntireColumn.Hidden = true;
  1381. continue;
  1382. }
  1383. for (int i = 0; i < datatb.Rows.Count; i++)
  1384. {
  1385. //获取单元格坐标
  1386. int[] pos;
  1387. if (es.RowDefine[j].Position == null)
  1388. {
  1389. pos = ExcelFunction.GetExcelFunction().GetPosition(es.Position);
  1390. if (!es.Rotate)
  1391. {
  1392. pos[0] = pos[0] + i;
  1393. pos[1] = pos[1] + j;
  1394. }
  1395. else
  1396. {
  1397. pos[1] = pos[1] + i;
  1398. pos[0] = pos[0] + j;
  1399. }
  1400. }
  1401. else
  1402. {
  1403. pos = ExcelFunction.GetExcelFunction().GetPosition(es.RowDefine[j].Position);
  1404. if (!es.Rotate)
  1405. {
  1406. pos[0] = pos[0] + i;
  1407. }
  1408. else
  1409. {
  1410. pos[1] = pos[1] + i;
  1411. }
  1412. }
  1413. //表中存在与XML中相同的列,将数据填充到对应的单元格中
  1414. if (datatb.Columns.Contains(es.RowDefine[j].DataName)
  1415. && !"DBNull".Equals(datatb.Rows[i][es.RowDefine[j].DataName].GetType().Name))
  1416. {
  1417. string sData = Convert.ToString(datatb.Rows[i][es.RowDefine[j].DataName]).Trim();
  1418. if (sData == string.Empty)
  1419. {
  1420. sData = es.NullString;
  1421. }
  1422. worksheet.Cells[pos[0], pos[1]] = sData;
  1423. }
  1424. intx = pos[0];
  1425. inty = pos[1];
  1426. }
  1427. }
  1428. //光标选中第一行
  1429. ((Range)worksheet.Rows["1:1", Type.Missing]).Select();
  1430. }
  1431. #endregion
  1432. #region private void ReadFixData(ReportTemplete, DataSet, SheetType, List<string[]>) 读取固定模式的值
  1433. /// <summary>
  1434. /// 读取固定模式的值
  1435. /// </summary>
  1436. /// <param name="rt"></param>
  1437. /// <param name="dsData"></param>
  1438. /// <param name="type"></param>
  1439. /// <param name="list"></param>
  1440. private void ReadFixData(ReportTemplete rt, DataSet dsData, SheetType type, List<string[]> list)
  1441. {
  1442. for (int iCount = 0; iCount < rt.FixedSection.Length; iCount++)
  1443. {
  1444. FixedSection fs = rt.FixedSection[iCount];
  1445. switch (type)
  1446. {
  1447. //一个sheet用一个配置的读取
  1448. case SheetType.OneSheetOneConfig:
  1449. Worksheet excelWorksheet = (Worksheet)m_excelSheets.get_Item(fs.SheetName);
  1450. DataTable dtData = new DataTable();
  1451. dtData.TableName = fs.Name;
  1452. ReadFixedSection(excelWorksheet, fs, dtData, list);
  1453. dsData.Tables.Add(dtData);
  1454. break;
  1455. //所有sheet用一个配置的读取
  1456. case SheetType.MoreSheetOneConfig:
  1457. foreach (Worksheet worksheet in m_excelSheets)
  1458. {
  1459. DataTable dataTable = new DataTable();
  1460. dataTable.TableName = fs.Name + "_" + worksheet.Name;
  1461. ReadFixedSection(worksheet, fs, dataTable, list);
  1462. dsData.Tables.Add(dataTable);
  1463. }
  1464. break;
  1465. default:
  1466. break;
  1467. }
  1468. }
  1469. }
  1470. #endregion
  1471. #region private void ReadExData(ReportTemplete, DataSet, SheetType, List<string[]>) 读取扩展模式的值
  1472. /// <summary>
  1473. /// 读取扩展模式的值
  1474. /// </summary>
  1475. /// <param name="rt"></param>
  1476. /// <param name="dsData"></param>
  1477. /// <param name="type"></param>
  1478. /// <param name="list"></param>
  1479. private void ReadExData(ReportTemplete rt, DataSet dsData, SheetType type, List<string[]> list)
  1480. {
  1481. for (int m = 0; m < rt.ExtendableSection.Length; m++)
  1482. {
  1483. ExtendableSection es = rt.ExtendableSection[m];
  1484. if (string.IsNullOrEmpty(es.Position))
  1485. {
  1486. es.Position = "A1";
  1487. }
  1488. int uniqueCount = 0;
  1489. foreach (RowDefine rd in es.RowDefine)
  1490. {
  1491. if (rd.Unique)
  1492. {
  1493. uniqueCount++;
  1494. }
  1495. }
  1496. switch (type)
  1497. {
  1498. //一个sheet用一个配置的读取
  1499. case SheetType.OneSheetOneConfig:
  1500. Worksheet excelWorksheet = (Worksheet)m_excelSheets.get_Item(es.SheetName);
  1501. DataTable dtData = new DataTable();
  1502. dtData.TableName = es.Name;
  1503. ReadExtandableSection(excelWorksheet, es, dtData, list, uniqueCount);
  1504. dsData.Tables.Add(dtData);
  1505. break;
  1506. //所有sheet用一个配置的读取
  1507. case SheetType.MoreSheetOneConfig:
  1508. foreach (Worksheet worksheet in m_excelSheets)
  1509. {
  1510. DataTable dataTable = new DataTable();
  1511. dataTable.TableName = es.Name + "_" + worksheet.Name;
  1512. ReadExtandableSection(worksheet, es, dataTable, list, uniqueCount);
  1513. dsData.Tables.Add(dataTable);
  1514. }
  1515. break;
  1516. default:
  1517. break;
  1518. }
  1519. if (!string.IsNullOrEmpty(ErrorMessage))
  1520. {
  1521. throw new EndOfStreamException(ErrorMessage);
  1522. }
  1523. }
  1524. }
  1525. #endregion
  1526. #region private void ReadFixedSection(_Worksheet, FixedSection, DataTable, List<string[]>) 读取一个具体数据区的值
  1527. /// <summary>
  1528. /// 读取一个具体数据区的值
  1529. /// </summary>
  1530. /// <param name="excelWorksheet"></param>
  1531. /// <param name="fs"></param>
  1532. /// <param name="dtData"></param>
  1533. /// <param name="list"></param>
  1534. private void ReadFixedSection(_Worksheet excelWorksheet, FixedSection fs, DataTable dtData, List<string[]> list)
  1535. {
  1536. //向DataTable添加一行空行
  1537. dtData.Rows.Add(dtData.NewRow());
  1538. //读取固定模式的值
  1539. if (fs.Rotate)
  1540. {
  1541. // 不规则,整体循环打印
  1542. Int32 iDistance = GetDistance(fs);
  1543. for (int i = 0; i < fs.Cell.Length; i++)
  1544. {
  1545. Cell c = fs.Cell[i];
  1546. dtData.Columns.Add(c.DataName);
  1547. string strPostion = (GetPostionX(c.Position) + (GetPostionY(c.Position) + iDistance));
  1548. Range excelCell = excelWorksheet.get_Range(strPostion, Missing.Value);
  1549. //单元格的值
  1550. string value = Convert.ToString(excelCell.Value2).Trim();
  1551. //必须输入check,为空的单元格坐标和正则表达式key添加到List<string[]>中
  1552. if (c.ValidationEmpty && string.IsNullOrEmpty(value))
  1553. {
  1554. string posion = ExcelFunction.GetExcelFunction().GetXByNum(excelCell.Column) + excelCell.Row;
  1555. list.Add(new string[] { posion, "IsNullOrEmpty", fs.SheetName });
  1556. }
  1557. //将格式错误的单元格坐标和正则表达式key添加到List<string[]>中
  1558. else if (!ValidationString(value, c.ValidationExpression) || !ValidationString(value, ValidationExpressionErrorChars))
  1559. {
  1560. string posion = ExcelFunction.GetExcelFunction().GetXByNum(excelCell.Column) + excelCell.Row;
  1561. list.Add(new string[] { posion, c.ValidationExpression, fs.SheetName });
  1562. }
  1563. //如果格式正确,将单元格的值填加到DataTable中
  1564. else
  1565. {
  1566. if (string.IsNullOrEmpty(value))
  1567. {
  1568. dtData.Rows[0][c.DataName] = DBNull.Value;
  1569. }
  1570. else
  1571. {
  1572. dtData.Rows[0][c.DataName] = value;
  1573. }
  1574. }
  1575. }
  1576. }
  1577. //如果格式正确,将单元格的值填加到DataTable中
  1578. else
  1579. {
  1580. for (int i = 0; i < fs.Cell.Length; i++)
  1581. {
  1582. Cell c = fs.Cell[i];
  1583. dtData.Columns.Add(c.DataName);
  1584. Range excelCell = excelWorksheet.get_Range(c.Position, Type.Missing);
  1585. if (string.IsNullOrEmpty(Convert.ToString(excelCell.Value2).Trim()))
  1586. {
  1587. dtData.Rows[0][c.DataName] = DBNull.Value;
  1588. }
  1589. else
  1590. {
  1591. dtData.Rows[0][c.DataName] = Convert.ToString(excelCell.Value2).Trim();
  1592. }
  1593. }
  1594. }
  1595. }
  1596. #endregion
  1597. #region private void ReadExtandableSection(_Worksheet, ExtendableSection, DataTable, List<string[]>) 读取一个具体数据区的值
  1598. /// <summary>
  1599. /// 读取一个具体数据区的值
  1600. /// </summary>
  1601. /// <param name="excelWorksheet"></param>
  1602. /// <param name="es"></param>
  1603. /// <param name="dtData"></param>
  1604. /// <param name="list"></param>
  1605. /// <param name="uniqueCount"></param>
  1606. private void ReadExtandableSection(_Worksheet excelWorksheet, ExtendableSection es, DataTable dtData, List<string[]> list, int uniqueCount)
  1607. {
  1608. for (int iCount = 0; iCount < es.RowDefine.Length; iCount++)
  1609. {
  1610. dtData.Columns.Add(es.RowDefine[iCount].DataName);
  1611. }
  1612. //循环添加值
  1613. int i = 0;
  1614. //不重复的行
  1615. List<string[]> rightUniqueList = new List<string[]>();
  1616. //重复的行
  1617. List<string[]> errorUniqueList = new List<string[]>();
  1618. while (true)
  1619. {
  1620. //DataTable中添加一行空行
  1621. dtData.Rows.Add(dtData.NewRow());
  1622. //标记是否整行为空
  1623. bool isEmpty = true;
  1624. //错误信息
  1625. List<string[]> errorList = new List<string[]>();
  1626. //唯一键
  1627. List<string> uniqueList = new List<string>();
  1628. //循环当行的所有单元格
  1629. for (int j = 0; j < es.RowDefine.Length; j++)
  1630. {
  1631. RowDefine rd = es.RowDefine[j];
  1632. //获取单元格的坐标
  1633. int[] pos;
  1634. if (rd.Position == null)
  1635. {
  1636. pos = ExcelFunction.GetExcelFunction().GetPosition(es.Position);
  1637. if (!es.Rotate)
  1638. {
  1639. pos[0] = pos[0] + i;
  1640. pos[1] = pos[1] + j;
  1641. }
  1642. else
  1643. {
  1644. pos[1] = pos[1] + i;
  1645. pos[0] = pos[0] + j;
  1646. }
  1647. }
  1648. else
  1649. {
  1650. pos = ExcelFunction.GetExcelFunction().GetPosition(rd.Position);
  1651. if (!es.Rotate)
  1652. {
  1653. pos[0] = pos[0] + i;
  1654. }
  1655. else
  1656. {
  1657. pos[1] = pos[1] + i;
  1658. }
  1659. }
  1660. //将单元格中的值设置到DataTable中
  1661. string strPostion = ExcelFunction.GetExcelFunction().GetXByNum(pos[1]) + pos[0];
  1662. Range excelCell = excelWorksheet.get_Range(strPostion, Missing.Value);
  1663. //单元格的值
  1664. string value = Convert.ToString(excelCell.Value2).Trim();
  1665. if (rd.ValidationEmpty && string.IsNullOrEmpty(value))
  1666. {
  1667. string posion = ExcelFunction.GetExcelFunction().GetXByNum(excelCell.Column) + excelCell.Row;
  1668. errorList.Add(new string[] { posion, "IsNullOrEmpty", es.SheetName });
  1669. }
  1670. //将格式错误的单元格坐标和正则表达式key添加到Hashtable中
  1671. else if (!ValidationString(value, rd.ValidationExpression) || !ValidationString(value, ValidationExpressionErrorChars))
  1672. {
  1673. string posion = ExcelFunction.GetExcelFunction().GetXByNum(excelCell.Column) + excelCell.Row;
  1674. errorList.Add(new string[] { posion, rd.ValidationExpression, es.SheetName });
  1675. }
  1676. else
  1677. {
  1678. //将单元格的值填加到DataTable中
  1679. if (string.IsNullOrEmpty(value))
  1680. {
  1681. dtData.Rows[i][rd.DataName] = DBNull.Value;
  1682. }
  1683. else
  1684. {
  1685. dtData.Rows[i][rd.DataName] = value;
  1686. }
  1687. if (rd.Unique)
  1688. {
  1689. uniqueList.Add(value);
  1690. }
  1691. }
  1692. //如果当前单元格不为空,将当行标记为非空行
  1693. if (isEmpty && !string.IsNullOrEmpty(value))
  1694. {
  1695. isEmpty = false;
  1696. }
  1697. }
  1698. //整行单元为空,删除最后一行并跳出循环
  1699. if (isEmpty)
  1700. {
  1701. dtData.Rows.RemoveAt(dtData.Rows.Count - 1);
  1702. break;
  1703. }
  1704. if (!string.IsNullOrEmpty(es.UploadMaxCount) && dtData.Rows.Count > Convert.ToInt32(es.UploadMaxCount))
  1705. {
  1706. string message = Convert.ToString(HttpContext.GetGlobalResourceObject(MessageFileName, MessageID));
  1707. ErrorMessage += es.SheetName
  1708. + ":"
  1709. + string.Format(message, "Upload", es.UploadMaxCount)
  1710. + "\\r\\n";
  1711. break;
  1712. }
  1713. //将格式错误的信息添加到List中
  1714. foreach (string[] str in errorList)
  1715. {
  1716. list.Add(str);
  1717. }
  1718. //联合主键字段数组
  1719. string[] unique = uniqueList.ToArray();
  1720. //如果重复
  1721. if (Contains(rightUniqueList, unique))
  1722. {
  1723. //没添加过将重复信息添加到List中
  1724. if (!Contains(errorUniqueList, unique))
  1725. {
  1726. errorUniqueList.Add(unique);
  1727. string uniqueColumn = string.Empty;
  1728. foreach (string str in unique)
  1729. {
  1730. uniqueColumn += "," + str;
  1731. }
  1732. if (uniqueColumn.Length > 0)
  1733. {
  1734. uniqueColumn = uniqueColumn.Substring(1);
  1735. }
  1736. list.Add(new string[] { uniqueColumn, "Exist", es.SheetName });
  1737. }
  1738. }
  1739. else if (uniqueCount > 0 && unique.Length == uniqueCount)
  1740. {
  1741. rightUniqueList.Add(unique);
  1742. }
  1743. i++;
  1744. }
  1745. }
  1746. #endregion
  1747. #region private void ResponseToClient(FileName, FileContent) 将服务器端文件以流的方式响应给客户端
  1748. /// <summary>
  1749. /// 将服务器端文件以流的方式响应给客户端
  1750. /// </summary>
  1751. /// <param name="aFileName">提供给客户端的默认文件名</param>
  1752. /// <param name="aFileContent">服务器上文件的内容</param>
  1753. private void ResponseToClient(string aFileName, string aFileContent)
  1754. {
  1755. ResponseToClient(aFileName, aFileContent, false);
  1756. }
  1757. #endregion
  1758. #region private void ResponseToClient(string, string, bool) 将服务器端文件以流的方式响应给客户端
  1759. /// <summary>
  1760. /// 将服务器端文件以流的方式响应给客户端
  1761. /// </summary>
  1762. /// <param name="aFileName">提供给客户端的默认文件名</param>
  1763. /// <param name="aContent">服务器上文件的全路径或内容</param>
  1764. /// <param name="bIsFile">服务器端信息是文件还是内容的方式</param>
  1765. private void ResponseToClient(string aFileName, string aContent, bool bIsFile)
  1766. {
  1767. HttpResponse httpResponse = HttpContext.Current.Response;
  1768. httpResponse.Clear();
  1769. httpResponse.Buffer = true;
  1770. httpResponse.Charset = "UTF-8";
  1771. httpResponse.ContentEncoding = Encoding.GetEncoding("UTF-8");
  1772. httpResponse.ContentType = "application/vnd.ms-excel";
  1773. string filenamewithext = aFileName + ".xls";
  1774. string savedName = HttpUtility.UrlEncode(filenamewithext);
  1775. httpResponse.AppendHeader("content-disposition", "attachment; filename=\"" + savedName + "\"");
  1776. if (bIsFile)
  1777. {
  1778. httpResponse.WriteFile(aContent);
  1779. }
  1780. else
  1781. {
  1782. httpResponse.Write(aContent);
  1783. }
  1784. httpResponse.Flush();
  1785. //文件状态时
  1786. if (bIsFile)
  1787. {
  1788. File.Delete(aContent);
  1789. }
  1790. }
  1791. #endregion
  1792. }
  1793. }