1. //1.添加引用-〉com-〉microsoft excel 11.0
  2. //2.若出现错误:命名空间“Microsoft.Office”中不存在类型或命名空间名称“Interop”(是缺少程序集引用吗?)
  3. //解决方法:先删除引用中的Excel,然后找到文件Microsoft.Office.Interop.Excel.dll,手动添加该文件的引用
  4.  
  5. using System;
  6. using System.Data;
  7. using System.Reflection;
  8. using System.IO;
  9. using Microsoft.Office.Core;
  10. using System.Windows.Forms;
  11. using Excel = Microsoft.Office.Interop.Excel;
  12.  
  13. namespace Wage.Common
  14. {
  15. /// <summary>
  16. /// 作者 Li Aimin (原创)
  17. /// 功能描述:C#对Excel报表进行操作
  18. /// 创建时间:2006-01-17, 修改时间:2007-1-14
  19. /// 说明:在工程中需要添加 Excel11.0对象库的引用(Office 2000为Excel9.0,Office XP为Excel10.0);
  20. /// 需要在Dcom中配置Excel应用程序的权限;
  21. /// 服务器需要安装Office2003
  22. /// </summary>
  23. public class ExcelLib
  24. {
  25. //http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dv_wrcore/html/wrgrfexcelapplicationobject.asp
  26. #region Variables
  27. private Excel.Application excelApplication = null;
  28. private Excel.Workbooks excelWorkBooks = null;
  29. private Excel.Workbook excelWorkBook = null;
  30. private Excel.Worksheet excelWorkSheet = null;
  31. private Excel.Range excelRange = null;//Excel Range Object,多种用途
  32. private Excel.Range excelCopySourceRange = null;//Excel Range Object
  33. private int excelActiveWorkSheetIndex; //活动工作表索引
  34. private string excelOpenFileName = ""; //操作Excel的路径
  35. private string excelSaveFileName = ""; //保存Excel的路径
  36. #endregion
  37.  
  38. #region Properties
  39. public int ActiveSheetIndex
  40. {
  41. get
  42. {
  43. return excelActiveWorkSheetIndex;
  44. }
  45. set
  46. {
  47. excelActiveWorkSheetIndex = value;
  48. }
  49. }
  50. public string OpenFileName
  51. {
  52. get
  53. {
  54. return excelOpenFileName;
  55. }
  56. set
  57. {
  58. excelOpenFileName = value;
  59. }
  60. }
  61. public string SaveFileName
  62. {
  63. get
  64. {
  65. return excelSaveFileName;
  66. }
  67. set
  68. {
  69. excelSaveFileName = value;
  70. }
  71. }
  72. #endregion
  73.  
  74. //
  75. //--------------------------------------------------------------------------------------------------------
  76. /// <summary>
  77. /// 构造函数;
  78. /// </summary>
  79. public ExcelLib()
  80. {
  81. excelApplication = null;//Excel Application Object
  82. excelWorkBooks = null;//Workbooks
  83. excelWorkBook = null;//Excel Workbook Object
  84. excelWorkSheet = null;//Excel Worksheet Object
  85. ActiveSheetIndex = 1; //默认值活动工作簿为第一个;设置活动工作簿请参阅SetActiveWorkSheet()
  86. }
  87. /// <summary>
  88. /// 以excelOpenFileName为模板新建Excel文件
  89. /// </summary>
  90. public bool OpenExcelFile()
  91. {
  92. if (excelApplication != null) CloseExcelApplication();
  93.  
  94. //检查文件是否存在
  95. if (excelOpenFileName == "")
  96. {
  97. throw new Exception("请选择文件!");
  98. }
  99. if (!File.Exists(excelOpenFileName))
  100. {
  101.  
  102. throw new Exception(excelOpenFileName + "该文件不存在!");//该异常如何处理,由什么处理????
  103. }
  104. try
  105. {
  106. excelApplication = new Excel.ApplicationClass();
  107. excelWorkBooks = excelApplication.Workbooks;
  108. excelWorkBook = ((Excel.Workbook)excelWorkBooks.Open(excelOpenFileName, Missing.Value, true, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value));
  109. excelWorkSheet = (Excel.Worksheet)excelWorkBook.Worksheets[excelActiveWorkSheetIndex];
  110. excelApplication.Visible = false;
  111.  
  112. return true;
  113. }
  114. catch (Exception e)
  115. {
  116. CloseExcelApplication();
  117. MessageBox.Show("(1)没有安装Excel 2003;(2)或没有安装Excel 2003 .NET 可编程性支持;\n详细信息:"
  118. +e.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
  119. //throw new Exception(e.Message);
  120. return false;
  121. }
  122. }
  123.  
  124. /// <summary>
  125. /// 读取一个Cell的值
  126. /// </summary>
  127. /// <param name="CellRowID">要读取的Cell的行索引</param>
  128. /// <param name="CellColumnID">要读取的Cell的列索引</param>
  129. /// <returns>Cell的值</returns>
  130. public string getOneCellValue(int CellRowID, int CellColumnID)
  131. {
  132. if (CellRowID <= 0)
  133. {
  134. throw new Exception("行索引超出范围!");
  135. }
  136. string sValue = "";
  137. try
  138. {
  139. sValue = ((Excel.Range)excelWorkSheet.Cells[CellRowID, CellColumnID]).Text.ToString();
  140. }
  141. catch (Exception e)
  142. {
  143. CloseExcelApplication();
  144. throw new Exception(e.Message);
  145. }
  146. return (sValue);
  147. }
  148. /// <summary>
  149. /// 读取一个连续区域的Cell的值(矩形区域,包含一行或一列,或多行,多列),返回一个一维字符串数组。
  150. /// </summary>
  151. /// <param name="StartCell">StartCell是要写入区域的左上角单元格</param>
  152. /// <param name="EndCell">EndCell是要写入区域的右下角单元格</param>
  153. /// <returns>值的集合</returns>
  154. public string[] getCellsValue(string StartCell, string EndCell)
  155. {
  156. string[] sValue = null;
  157. //try
  158. //{
  159. excelRange = (Excel.Range)excelWorkSheet.get_Range(StartCell, EndCell);
  160. sValue = new string[excelRange.Count];
  161. int rowStartIndex = ((Excel.Range)excelWorkSheet.get_Range(StartCell, StartCell)).Row; //起始行号
  162. int columnStartIndex = ((Excel.Range)excelWorkSheet.get_Range(StartCell, StartCell)).Column; //起始列号
  163. int rowNum = excelRange.Rows.Count; //行数目
  164. int columnNum = excelRange.Columns.Count; //列数目
  165. int index = 0;
  166. for (int i = rowStartIndex; i < rowStartIndex + rowNum; i++)
  167. {
  168. for (int j = columnStartIndex; j < columnNum + columnStartIndex; j++)
  169. {
  170. //读到空值null和读到空串""分别处理
  171. sValue[index] = ((Excel.Range)excelWorkSheet.Cells[i, j]).Text.ToString();
  172. index++;
  173. }
  174. }
  175. //}
  176. //catch (Exception e)
  177. //{
  178. // CloseExcelApplication();
  179. // throw new Exception(e.Message);
  180. //}
  181.  
  182. return (sValue);
  183. }
  184.  
  185. /// <summary>
  186. /// 读取所有单元格的数据(矩形区域),返回一个datatable.假设所有单元格靠工作表左上区域。
  187. /// </summary>
  188. public DataTable getAllCellsValue()
  189. {
  190. int columnCount = getTotalColumnCount();
  191. int rowCount = getTotalRowCount();
  192. DataTable dt = new DataTable();
  193. //设置datatable列的名称
  194. for (int columnID = 1; columnID <= columnCount; columnID++)
  195. {
  196. dt.Columns.Add(((Excel.Range)excelWorkSheet.Cells[1, columnID]).Text.ToString());
  197. }
  198.  
  199. for (int rowID = 2; rowID <= rowCount; rowID++)
  200. {
  201. DataRow dr = dt.NewRow();
  202. for (int columnID = 1; columnID <= columnCount; columnID++)
  203. {
  204. dr[columnID - 1] = ((Excel.Range)excelWorkSheet.Cells[rowID, columnID]).Text.ToString();
  205. //读到空值null和读到空串""分别处理
  206. }
  207. dt.Rows.Add(dr);
  208. }
  209. return (dt);
  210. }
  211. public int getTotalRowCount()
  212. {//当前活动工作表中有效行数(总行数)
  213. int rowsNumber = 0;
  214. try
  215. {
  216. while (true)
  217. {
  218. if (((Excel.Range)excelWorkSheet.Cells[rowsNumber + 1, 1]).Text.ToString().Trim() == "" &&
  219. ((Excel.Range)excelWorkSheet.Cells[rowsNumber + 2, 1]).Text.ToString().Trim() == "" &&
  220. ((Excel.Range)excelWorkSheet.Cells[rowsNumber + 3, 1]).Text.ToString().Trim() == "")
  221. break;
  222. rowsNumber++;
  223. }
  224. }
  225. catch
  226. {
  227. return -1;
  228. }
  229. return rowsNumber;
  230. }
  231. /// <summary>
  232. /// 当前活动工作表中有效列数(总列数)
  233. /// </summary>
  234. /// <param></param>
  235. public int getTotalColumnCount()
  236. {
  237. int columnNumber = 0;
  238. try
  239. {
  240. while (true)
  241. {
  242. if (((Excel.Range)excelWorkSheet.Cells[1, columnNumber + 1]).Text.ToString().Trim() == "" &&
  243. ((Excel.Range)excelWorkSheet.Cells[1, columnNumber + 2]).Text.ToString().Trim() == "" &&
  244. ((Excel.Range)excelWorkSheet.Cells[1, columnNumber + 3]).Text.ToString().Trim() == "")
  245. break;
  246. columnNumber++;
  247. }
  248. }
  249. catch
  250. {
  251. return -1;
  252. }
  253. return columnNumber;
  254. }
  255.  
  256. /// <summary>
  257. /// 向一个Cell写入数据
  258. /// </summary>
  259. /// <param name="CellRowID">CellRowID是cell的行索引</param>
  260. /// <param name="CellColumnID">CellColumnID是cell的列索引</param>
  261. ///<param name="Value">要写入该单元格的数据值</param>
  262. public void setOneCellValue(int CellRowID, int CellColumnID, string Value)
  263. {
  264. try
  265. {
  266. excelRange = (Excel.Range)excelWorkSheet.Cells[CellRowID, CellColumnID];
  267. excelRange.Value2 = Value;//Value2?
  268. //Gets or sets the value of the NamedRange control.
  269. //The only difference between this property and the Value property is that Value2 is not a parameterized property.
  270. excelRange = null;
  271. }
  272. catch (Exception e)
  273. {
  274. CloseExcelApplication();
  275. throw new Exception(e.Message);
  276. }
  277. }
  278. /// <summary>
  279. /// 设置活动工作表
  280. /// </summary>
  281. /// <param name="SheetIndex">要设置为活动工作表的索引值</param>
  282. public void SetActiveWorkSheet(int SheetIndex)
  283. {
  284. if (SheetIndex <= 0)
  285. {
  286. throw new Exception("索引超出范围!");
  287. }
  288. try
  289. {
  290. ActiveSheetIndex = SheetIndex;
  291. excelWorkSheet = (Excel.Worksheet)excelWorkBook.Worksheets[ActiveSheetIndex];
  292. }
  293. catch (Exception e)
  294. {
  295. CloseExcelApplication();
  296. throw new Exception(e.Message);
  297. }
  298. }
  299. /// <summary>
  300. /// 向连续区域一次性写入数据;只有在区域连续和写入的值相同的情况下可以使用方法
  301. /// </summary>
  302. /// <param name="StartCell">StartCell是要写入区域的左上角单元格</param>
  303. /// <param name="EndCell">EndCell是要写入区域的右下角单元格</param>
  304. /// <param name="Value">要写入指定区域所有单元格的数据值</param>
  305. public void setCellsValue(string StartCell, string EndCell, string Value)
  306. {
  307. try
  308. {
  309. excelRange = excelWorkSheet.get_Range(StartCell, EndCell);
  310. excelRange.Value2 = Value;
  311. excelRange = null;
  312. }
  313. catch (Exception e)
  314. {
  315. CloseExcelApplication();
  316. throw new Exception(e.Message);
  317. }
  318. }
  319. /// <summary>
  320. /// 给一行写数据
  321. /// </summary>
  322. public void setOneLineValues(int LineID, int StartCellColumnID, int EndCellColumnID, string[] Values)////已经测试
  323. {
  324. //用1-19号元素
  325.  
  326. //if (Values.Length!=EndCellColumnID-StartCellColumnID)
  327. //{
  328. // throw new Exception("单元格数目与提供的值的数目不一致!");
  329. //}
  330. for (int i = StartCellColumnID; i <= EndCellColumnID; i++)
  331. {
  332. setOneCellValue(LineID, i, Values[i]);
  333. }
  334. }
  335. public void setCellsBorder(string startCell, string endCell)
  336. {
  337. //设置某个范围内的单元格的边框
  338. excelRange = excelWorkSheet.get_Range(startCell, endCell);
  339. excelRange.Borders[Excel.XlBordersIndex.xlEdgeLeft].LineStyle = Excel.XlLineStyle.xlContinuous;
  340. excelRange.Borders[Excel.XlBordersIndex.xlEdgeTop].LineStyle = Excel.XlLineStyle.xlContinuous;
  341. excelRange.Borders[Excel.XlBordersIndex.xlEdgeRight].LineStyle = Excel.XlLineStyle.xlContinuous;
  342. excelRange.Borders[Excel.XlBordersIndex.xlEdgeBottom].LineStyle = Excel.XlLineStyle.xlContinuous;
  343. excelRange.Borders[Excel.XlBordersIndex.xlInsideVertical].LineStyle = Excel.XlLineStyle.xlContinuous;
  344. //excelRange.Borders[Excel.XlBordersIndex.xlInsideHorizontal].LineStyle = Excel.XlLineStyle.xlContinuous;
  345. }
  346.  
  347. public void setOneCellBorder(int CellRowID, int CellColumnID)
  348. {
  349. //设置某个单元格的边框
  350. excelRange = (Excel.Range)excelWorkSheet.Cells[CellRowID, CellColumnID];
  351.  
  352. excelRange.Borders[Excel.XlBordersIndex.xlEdgeLeft].LineStyle = Excel.XlLineStyle.xlContinuous;
  353. excelRange.Borders[Excel.XlBordersIndex.xlEdgeTop].LineStyle = Excel.XlLineStyle.xlContinuous;
  354. excelRange.Borders[Excel.XlBordersIndex.xlEdgeRight].LineStyle = Excel.XlLineStyle.xlContinuous;
  355. excelRange.Borders[Excel.XlBordersIndex.xlEdgeBottom].LineStyle = Excel.XlLineStyle.xlContinuous;
  356. //excelRange.Borders[Excel.XlBordersIndex.xlInsideVertical].LineStyle = Excel.XlLineStyle.xlContinuous;
  357. //excelRange.Borders[Excel.XlBordersIndex.xlInsideHorizontal].LineStyle = Excel.XlLineStyle.xlContinuous;
  358. }
  359.  
  360. public void SetColumnWidth(string startCell, string endCell, int size)
  361. {
  362. //设置某个范围内的单元格的列的宽度
  363. excelRange = excelWorkSheet.get_Range(startCell, endCell);
  364. excelRange.ColumnWidth = size;
  365. }
  366.  
  367. public void SetOneCellFont(int CellRowID, int CellColumnID, string fontName, int fontSize)
  368. {
  369. excelRange = (Excel.Range)excelWorkSheet.Cells[CellRowID, CellColumnID];
  370. excelRange.Font.Name = fontName;
  371. excelRange.Font.Size = fontSize;
  372. }
  373.  
  374. public void SetOneCellHorizontalAlignment(int CellRowID, int CellColumnID, Excel.Constants alignment)
  375. {
  376. excelRange = (Excel.Range)excelWorkSheet.Cells[CellRowID, CellColumnID];
  377. excelRange.HorizontalAlignment = alignment;
  378.  
  379. }
  380.  
  381. public void SetOneCellColumnWidth(int CellRowID, int CellColumnID, int size)
  382. {
  383. //设置某个单元格的列的宽度
  384. excelRange = (Excel.Range)excelWorkSheet.Cells[CellRowID, CellColumnID];
  385. excelRange.ColumnWidth = size;
  386.  
  387. }
  388.  
  389. /// <summary>
  390. /// 设置一个Cell的数据格式
  391. /// </summary>
  392. /// <param name="CellRowID">CellRowID是cell的行索引</param>
  393. /// <param name="CellColumnID">CellColumnID是cell的列索引</param>
  394. ///<param name="Value">数据格式</param>
  395. public void setOneCellNumberFormat(int CellRowID, int CellColumnID, string numberFormat)
  396. {
  397. try
  398. {
  399. excelRange = (Excel.Range)excelWorkSheet.Cells[CellRowID, CellColumnID];
  400. excelRange.NumberFormatLocal = numberFormat;
  401.  
  402. excelRange = null;
  403. }
  404. catch (Exception e)
  405. {
  406. CloseExcelApplication();
  407. throw new Exception(e.Message);
  408. }
  409. }
  410. public void SetRowHeight(string startCell, string endCell, int size)
  411. {
  412. //设置某个范围内的单元格的行的高度
  413. excelRange = excelWorkSheet.get_Range(startCell, endCell);
  414. excelRange.RowHeight = size;
  415.  
  416. }
  417. public void SetRowHeight(int CellRowID, int CellColumnID, float size)
  418. {
  419. //设置某个范围内的单元格的行的高度
  420. excelRange = (Excel.Range)excelWorkSheet.Cells[CellRowID, CellColumnID];
  421. excelRange.RowHeight = size;
  422.  
  423. }
  424. public void SetOneCellRowHeight(int CellRowID, int CellColumnID, int size)
  425. {
  426. //设置某个单元格的行的高度
  427. excelRange = (Excel.Range)excelWorkSheet.Cells[CellRowID, CellColumnID];
  428. excelRange.RowHeight = size;
  429.  
  430. }
  431.  
  432. /// <summary>
  433. /// 拷贝区域.限制:在同一个工作表中复制
  434. /// </summary>
  435. /// <param name="SourceStart">源区域的左上角单元格</param>
  436. /// <param name="SourceEnd">源区域的右下角单元格</param>
  437. /// <param name="DesStart">目标区域的左上角单元格</param>
  438. /// <param name="DesEnd">目标区域的右下角单元格</param>
  439. public void CopyCells(string SourceStart, string SourceEnd, string DesStart, string DesEnd)
  440. {
  441. try
  442. {
  443. excelCopySourceRange = excelWorkSheet.get_Range(SourceStart, SourceEnd);
  444. excelRange = excelWorkSheet.get_Range(DesStart, DesEnd);
  445. excelCopySourceRange.Copy(excelRange);
  446.  
  447. excelCopySourceRange = null;
  448. excelRange = null;
  449. }
  450. catch (Exception e)
  451. {
  452. CloseExcelApplication();
  453. throw new Exception(e.Message);
  454. }
  455. }
  456. public void CopyWorksheet(int SourceWorksheetIndex, int DesWorksheetIndex)
  457. {
  458. try
  459. {
  460. // Sheets("Sheet2").Select
  461. //Sheets("Sheet2").Copy After:=Sheets(3)
  462. Excel.Worksheet sheetSource = (Excel.Worksheet)excelWorkBook.Worksheets[SourceWorksheetIndex];
  463. sheetSource.Select(Missing.Value);
  464. Excel.Worksheet sheetDest = (Excel.Worksheet)excelWorkBook.Worksheets[DesWorksheetIndex];
  465. sheetSource.Copy(Missing.Value, sheetDest);
  466. }
  467. catch (Exception e)
  468. {
  469. CloseExcelApplication();
  470. throw new Exception(e.Message);
  471. }
  472. }
  473.  
  474. /// <summary>
  475. /// 插入一行
  476. /// </summary>
  477. /// <param name="CellRowID">要插入所在行的索引位置,插入后其原有行下移</param>
  478. /// <param name="RowNum">要插入行的个数</param>
  479. public void InsertRow(int CellRowID, int RowNum)//插入空行
  480. {
  481. if (CellRowID <= 0)
  482. {
  483. throw new Exception("行索引超出范围!");
  484. }
  485. if (RowNum <= 0)
  486. {
  487. throw new Exception("插入行数无效!");
  488. }
  489. try
  490. {
  491. excelRange = (Excel.Range)excelWorkSheet.Rows[CellRowID, Missing.Value];
  492. for (int i = 0; i < RowNum; i++)
  493. {
  494. excelRange.Insert(Excel.XlDirection.xlDown, Missing.Value);
  495. }
  496. excelRange = null;
  497. }
  498. catch (Exception e)
  499. {
  500. CloseExcelApplication();
  501. throw new Exception(e.Message);
  502. }
  503. }
  504.  
  505. /// <summary>
  506. /// 保存Excel文件
  507. /// </summary>
  508.  
  509. public Excel.Range FindFirstRange(Excel.Range xlRange, string FindText)//查找//没有测试
  510. {
  511. //查找第一个满足的区域
  512. //Search for the first match
  513. Excel.Range firstFind = null;
  514. firstFind = xlRange.Find(FindText, Missing.Value, Excel.XlFindLookIn.xlValues, Excel.XlLookAt.xlPart, Excel.XlSearchOrder.xlByRows, Excel.XlSearchDirection.xlNext, false, Missing.Value, Missing.Value);
  515. return firstFind; //如果没找到,返回空
  516. }
  517. //http://msdn.microsoft.com/library/en-us/dv_wrcore/html/wrtskHowToSearchForTextInWorksheetRanges.asp?frame=true
  518.  
  519. /// <summary>
  520. /// 当前活动工作表中有效行数(总行数)
  521. /// </summary>
  522. /// <param></param>
  523.  
  524. /// <summary>
  525. /// 判断单元格是否有数据
  526. /// </summary>
  527. public bool CellValueIsNull(int CellLineID, int CellColumnID)////已经测试
  528. {
  529.  
  530. //判断单元格是否有数据
  531. if ((((Excel.Range)excelWorkSheet.Cells[CellLineID, CellColumnID]).Text.ToString().Trim() != ""))
  532. return false;
  533. return true;
  534. }
  535.  
  536. public void newWorkbook(string excelTemplate, string fileName)
  537. {
  538. //以excelTemplate为模板新建文件fileName
  539. //excelApplication.
  540. excelWorkBook = excelWorkBooks.Add(excelTemplate);
  541. SaveFileName = "";
  542. SaveExcel();
  543. }
  544. public void newWorksheet()
  545. {
  546. excelWorkBook.Worksheets.Add(Missing.Value, Missing.Value, 1, Missing.Value);
  547. }
  548. public void setWorksheetName(int sheetIndex, string worksheetName)
  549. {
  550. // Missing.Value
  551. Excel._Worksheet sheet = (Excel._Worksheet)(excelWorkBook.Worksheets[(object)sheetIndex]);
  552. sheet.Name = worksheetName;
  553. }
  554.  
  555. public void mergeOneLineCells(string startCell, string endCell)
  556. {
  557. //合并一行单元格
  558. excelRange = excelWorkSheet.get_Range(startCell, endCell);
  559. //excelRange.Merge(true);
  560. excelRange.MergeCells = true;
  561. }
  562.  
  563. public void HorizontalAlignmentCells(string startCell, string endCell, Excel.Constants alignment)
  564. {
  565. //水平对齐一行单元格
  566. excelRange = excelWorkSheet.get_Range(startCell, endCell);
  567. excelRange.HorizontalAlignment = alignment;
  568. }
  569.  
  570. public void VerticalAlignmentCells(string startCell, string endCell, Excel.Constants alignment)
  571. {
  572. //垂直对齐一行单元格
  573. excelRange = excelWorkSheet.get_Range(startCell, endCell);
  574. excelRange.VerticalAlignment = alignment;
  575. }
  576.  
  577. //实现列号-〉字母 (26-〉Z,27->AA)
  578. private string ConvertColumnIndexToChar(int columnIndex)
  579. {
  580. if (columnIndex < 1 || columnIndex > 256)
  581. {
  582. MessageBox.Show("columnIndex=" + columnIndex + ",超出了有效范围(1-256)");
  583. return "A";
  584. }
  585. if (columnIndex >= 1 && columnIndex <= 26)//1--26
  586. {
  587. return "AA";
  588. }
  589. if (columnIndex >= 27 && columnIndex <= 256)//27--256
  590. {
  591. return "AA";
  592. }
  593. return "A";
  594. }
  595. //字母-〉列号 Z-〉26
  596. public void SaveExcel()
  597. {
  598. if (excelSaveFileName == "")
  599. {
  600. throw new Exception("未指定要保存的文件名");
  601. }
  602. try
  603. {
  604. //excelWorkSheet.SaveAs(excelSaveFileName, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Excel.XlSaveAsAccessMode.xlNoChange, Missing.Value, Missing.Value, Missing.Value);
  605. excelWorkSheet.SaveAs(excelSaveFileName, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Excel.XlSaveAsAccessMode.xlNoChange, Missing.Value, Missing.Value, Missing.Value);
  606.  
  607. }
  608. catch (Exception e)
  609. {
  610. CloseExcelApplication();
  611. throw new Exception(e.Message);
  612. }
  613. }
  614.  
  615. //--------------------------------------------------------------------------------------------------------
  616. /// <summary>
  617. /// 保存Excel文件,格式xml.
  618. /// </summary>
  619. public void SaveExcelAsXML()
  620. {
  621. if (excelSaveFileName == "")
  622. {
  623. throw new Exception("未指定要保存的文件名");
  624. }
  625. try
  626. {
  627. //excelWorkSheet.SaveAs(excelSaveFileName, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Excel.XlSaveAsAccessMode.xlNoChange, Missing.Value, Missing.Value, Missing.Value);
  628. excelWorkSheet.SaveAs(excelSaveFileName, Microsoft.Office.Interop.Excel.XlFileFormat.xlXMLSpreadsheet, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Excel.XlSaveAsAccessMode.xlNoChange, Missing.Value, Missing.Value, Missing.Value);
  629.  
  630. }
  631. catch (Exception e)
  632. {
  633. CloseExcelApplication();
  634. throw new Exception(e.Message);
  635. }
  636. }
  637. //--------------------------------------------------------------------------------------------------------
  638. /// <summary>
  639. /// 关闭Excel文件,释放对象;最后一定要调用此函数,否则会引起异常
  640. /// </summary>
  641. /// <param></param>
  642. public void CloseExcelApplication()
  643. {
  644. try
  645. {
  646. excelWorkBooks = null;
  647. excelWorkBook = null;
  648. excelWorkSheet = null;
  649. excelRange = null;
  650. if (excelApplication != null)
  651. {
  652. excelApplication.Workbooks.Close();
  653. //Object missing = Type.Missing;
  654. excelApplication.Quit();
  655. excelApplication = null;
  656. //ReleaseAllRef(excelApplication);//Error
  657.  
  658. }
  659. }
  660. finally
  661. {
  662. GC.Collect();
  663. GC.WaitForPendingFinalizers();
  664. GC.Collect();
  665. GC.WaitForPendingFinalizers();
  666. }
  667. }
  668. private void ReleaseAllRef(Object obj)
  669. {//ReleaseComObject()方法可以使RCW减少一个对COM组件的引用,并返回减少一个引用后RCW对COM组件的剩余引用数量。
  670. //我们用一个循环,就可以让RCW将所有对COM组件的引用全部去掉。
  671. try
  672. {
  673. while (System.Runtime.InteropServices.Marshal.ReleaseComObject(obj) > 1) ;
  674. }
  675. finally
  676. {
  677. obj = null;
  678. }
  679. }
  680.  
  681. }
  682. }

  

  1. 无法嵌入互操作类型“Microsoft.Office.Interop.Excel.ApplicationClass”。请改用适用的接口。
  2.  
  3. winform下对datagridview进行导出时候,写了一句:
  4. Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.ApplicationClass();
  5.  
  6. 导致结果如下:
  7.  
  8. 类型“Microsoft.Office.Interop.Excel.ApplicationClass”未定义构造函数
  9. 无法嵌入互操作类型“Microsoft.Office.Interop.Excel.ApplicationClass”。请改用适用的接口。
  10.  
  11. 解决办法是将引用的DLLMicrosoft.Office.Interop.Excel;的嵌入互操作类型改为false,就可以了。
  12.  
  13. 下载地址:https://files.cnblogs.com/files/emanlee/ExcelLib.rar
  14.  
  15. 转载链接:http://www.cnblogs.com/emanlee/archive/2007/05/31/766520.html
  16.  
  17. 引用代码
  1. static void Main(string[] args)
  2. {
  3. ExcelLib excel = new ExcelLib();
  4. excel.OpenFileName = @"C:\Users\lc\Desktop\test.xlsx";
  5. excel.SaveFileName = @"C:\Users\lc\Desktop\test002.xlsx";
  6. excel.OpenExcelFile();
  7. int columns = excel.getTotalColumnCount();
  8. int rows = excel.getTotalRowCount();
  9. string value = excel.getOneCellValue(1, 1);
  10. for (int row = 1; row <= rows; row++)
  11. {
  12. for (int column = 1; column <= columns; column++)
  13. {
  14. string xx = excel.getOneCellValue(row, column);
  15. Console.WriteLine(xx);
  16. }
  17. }
  18.  
  19. excel.setOneCellValue(4, 4, "xyz222");
  20. excel.SaveExcel();
  21. }

  

[转]C#对Excel报表进行操作(读写和基本操作)的更多相关文章

  1. excel、xls文件读写操作

    python 常用的excel.xls文件读写操作,有两个模块 xlrd:读 xlwt:写 本次先写一个读的例子: class CaseData(object): def __init__(self, ...

  2. 在.NET中使用EPPlus生成Excel报表 .

    --摘抄自:http://blog.csdn.net/zhoufoxcn/article/details/14112473 在开发.NET应用中可能会遇到需要生成带图表(Chart)的Excel报表的 ...

  3. Java使用POI实现数据导出excel报表

    Java使用POI实现数据导出excel报表 在上篇文章中,我们简单介绍了java读取word,excel和pdf文档内容 ,但在实际开发中,我们用到最多的是把数据库中数据导出excel报表形式.不仅 ...

  4. 10、借助POI实现Java生成并打印excel报表(1)

    10.1.了解 Apache POI 实际开发中,用到最多的是把数据库中数据导出生成报表,尤其是在生产管理或者财务系统中用的非常普遍.生成报表格式一般是EXCEL或者PDF .利用Apache  PO ...

  5. C#对Excel的图文操作

    1.打印Excel 目前的商业工具如水晶报表,ActiveReport等,都提供了灵活,强大的功能,但是对于比较特殊化的表格,特别是国内的一些应用,都是一个个的格子组成的,这样要是用线来一根根画就比较 ...

  6. ASP.NET MVC 4.0 中使用NPOI 2.2.0 按模板生成Excel报表

    使用 NPOI 你就可以在没有安装 Office 或者相应环境的机器上对 WORD/EXCEL 文档进行读写.NPOI是构建在POI 3.x版本之上的,它可以在没有安装Office的情况下对Word/ ...

  7. 如何在没有安装微软Excel环境下操作Excel文件?

    在以前接触的项目中,由于很多客户对微软Excel的操作比较熟练,客户经常要求系统支持对Excel文件的读写.用.NET传统方法对Excel进行读写时,往往会涉及到不同版本兼容的问题,导致在本地测试一切 ...

  8. ASP.NET打印EXCEl报表技术总结

    序言:我们在做企业项目或者一些管理系统的时候往往会用到导出到excel报表这项功能,下面我介绍的是用windows自带的excel来打印 首先必须引入:Interop.Excel.dll.Intero ...

  9. xBIM IFC 输出 Excel 报表

    目录 xBIM 应用与学习 (一) xBIM 应用与学习 (二) xBIM 基本的模型操作 xBIM 日志操作 XBIM 3D 墙壁案例 xBIM 格式之间转换 xBIM 使用Linq 来优化查询 x ...

随机推荐

  1. Codeforces 1105E 最大独立集 状态DP 中途相遇法

    题意:你有一个字符串, 有两种操作,一种是改变字符串,一种是某个用户询问这个字符串,如果一个用户每次查询字符串的时候都是他的用户名,他就会高兴.问最多有多少个用户会高兴? 题意:容易发现,在两个1操作 ...

  2. jieba分词单例模式及linux权限不够情况下tmp_dir自定义

    在linux环境下,没有root权限的情况下,有时会碰到如下问题: Building prefix dict from the default dictionary ... Loading model ...

  3. 八、结构模式之组合(Composite)模式

    组合模式属于对象的结构模式,有时又叫做部分-整体模式,组合模式将对象组织到树结构中,可以用来描述整体与部分的联系.其可以使客户端将单纯元素和组合元素同等对待. 当需求中是体现部分与整体层次的结构时,以 ...

  4. 初撩RESTful

    1. 什么是RESTful? 一种软件架构风格,设计风格,用于客户端和服务端交互类的架构. 一组架构约束条件和原则 2. 什么是RESTful架构? 客户端通过http动词(get/post等)对服务 ...

  5. 【leetcode】966. Vowel Spellchecker

    题目如下: Given a wordlist, we want to implement a spellchecker that converts a query word into a correc ...

  6. 笨办法学Python记录--习题38-40,复习前面,运用list操作函数

    #习题38 区分列表和字符串,用到了split(字符串专用函数),join.append.pop(这些是list操作函数) ten_things = "Apples Oranges Crow ...

  7. ACdream 1157 (cdq分治)

    题目链接 Segments Time Limit: 4000/2000MS (Java/Others)Memory Limit: 20000/10000KB (Java/Others) Problem ...

  8. Golang 标准库提供的Log(一)

      原创作品,允许转载,转载时请务必以超链接形式标明文章 原始出处 .作者信息和本声明.否则将追究法律责任.http://gotaly.blog.51cto.com/8861157/1405754 G ...

  9. Vue中时间的设置

    设置默认属性ct_month: null 方法: //默认显示今天getdatatime(){ this.ct_month= new Date(); }, //默认显示昨天getdatatime(){ ...

  10. XML XPATH simpleXML

    XPath 通过DOM结构定位节点,在数据量很大的情况下速度下降的很厉害.解决方法是XPath.Xpath的作用:用于快速定位节点 position()是节点的位置,节点的位置是从1开始 simple ...