C# 读写xml、excel、word、access

这里只是起个头,不做深入展开,方便以后用到参考

读写xml,主要使用.net  的xml下的document

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Xml;
using System.Xml.Serialization;

  1. public static void GetAreaCodes(string path,out string[] areaCodes ,out string[] pointCodes)
  2. {
  3. if (File.Exists(path))
  4. {
  5. try
  6. {
  7. XmlDocument xml = new XmlDocument();
  8. xml.LoadXml(path);
  9. List<string> areas = new List<string>();
  10. var areanode = xml.SelectSingleNode("areaRoot");
  11. var elements = areanode.ChildNodes;
  12. foreach (var element in elements)
  13. {
  14. areas.Add((element as XmlElement).InnerXml);
  15. }
  16. List<string> points = new List<string>();
  17. var pointnode = xml.SelectSingleNode("pointRoot");
  18. elements = areanode.ChildNodes;
  19. foreach (var element in elements)
  20. {
  21. points.Add((element as XmlElement).InnerXml);
  22. }
  23. areaCodes = areas.ToArray();
  24. pointCodes = points.ToArray();
  25. }
  26. catch
  27. {
  28. pointCodes = new[] { "GPS点", "建屋", "等级公路" };
  29. areaCodes = new[] { "砖房", "阳台", "建屋", "地类界", "变电房" };
  30. }
  31.  
  32. }
  33. else
  34. {
  35. pointCodes = new[] { "GPS点", "建屋", "等级公路" };
  36. areaCodes = new[] { "砖房", "阳台", "建屋", "地类界", "变电房" };
  37. }
  38.  
  39. }
  40.  
  41. public static void WriteAreaCodes(string path, string[] areaCodes, string[] pointCodes)
  42. {
  43. try
  44. {
  45. XmlDocument xml=new XmlDocument();
  46. XmlDeclaration xmlDeclaration = xml.CreateXmlDeclaration("1.0", "utf-8","yes");
  47. XmlNode Codes = xml.CreateElement("Codes");
  48. xml.AppendChild(xmlDeclaration);
  49. xml.AppendChild(Codes);
  50. XmlNode areaRoot = xml.CreateElement("areaRoot");
  51. foreach (var str in areaCodes)
  52. {
  53. XmlElement areaCode = xml.CreateElement("areaCode");
  54. areaCode.InnerXml=str;
  55. areaRoot.AppendChild(areaCode);
  56. }
  57. Codes.AppendChild(areaRoot);
  58. XmlNode pointRoot = xml.CreateElement("pointRoot");
  59. foreach (var str in pointCodes)
  60. {
  61. XmlElement pointCode = xml.CreateElement("pointCode");
  62. pointCode.InnerXml=str;
  63. pointRoot.AppendChild(pointCode);
  64. }
  65. Codes.AppendChild(pointRoot);
  66. xml.Save(path);
  67.  
  68. }
  69. catch (Exception ex)
  70. {
  71. throw ex;
  72. }
  73.  
  74. }

读写excel,调用com,读写比较慢

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using SDataTable = System.Data.DataTable;
using Microsoft.Office.Interop.Excel;
using System.Data;
using System.Reflection;

  1. public class CExcel
  2. {
  3.  
  4. private string filepath = "";
  5. private Microsoft.Office.Interop.Excel.Application excel;
  6. private Workbook workbook = null;
  7. public CExcel()
  8. {
  9. excel = new Application();
  10. excel.Visible = false;
  11. excel.DisplayAlerts = false;
  12. }
  13. /// <summary>
  14. /// 打开Excel文件
  15. /// </summary>
  16. /// <param name="filename">文件名</param>
  17. public void OpenExcel(string filename)
  18. {
  19. workbook = excel.Application.Workbooks.Open(filename);
  20. }
  21. /// <summary>
  22. /// 获取一个sheet
  23. /// </summary>
  24. /// <param name="index">sheet索引</param>
  25. /// <param name="sheetname">sheet名,默认为空,为空以第一个参数为准,否则以名为准</param>
  26. /// <returns>返回worksheet对象</returns>
  27. public Worksheet GetSheet(int index,string sheetname=null)
  28. {
  29. if (workbook == null) return null;
  30. var sheet = workbook.Worksheets.get_Item(index);
  31. if (sheetname == null) return sheet;
  32. foreach (var sh in workbook.Worksheets)
  33. {
  34. sheet = sh as Worksheet;
  35. if (sheet.Name == sheetname) break;
  36. }
  37. return sheet;
  38.  
  39. }
  40. /// <summary>
  41. /// 关闭workbook
  42. /// </summary>
  43. public void Closeworkbook()
  44. {
  45. if (workbook != null) workbook.Close();
  46. }
  47. /// <summary>
  48. /// 释放excel对象
  49. /// </summary>
  50. public void Dispose()
  51. {
  52. excel.Quit();
  53. }
  54. /// <summary>
  55. /// 读取一个sheet内容
  56. /// </summary>
  57. /// <param name="psheet"></param>
  58. /// <param name="index"></param>
  59. /// <returns></returns>
  60. public SDataTable GetTableFromSheet(Worksheet psheet, int index = )
  61. {
  62. int rowcount = psheet.UsedRange.Cells.Rows.Count;
  63. int colcount = psheet.UsedRange.Columns.Count;
  64. Range range;
  65. SDataTable dt = new SDataTable();
  66. dt.TableName = psheet.Parent.Name + psheet.Name;
  67. DataColumn dc;
  68. int ColumnID = ;
  69. int col = ;
  70. while (col <= colcount)
  71. {
  72. dc = new DataColumn();
  73. dc.DataType = typeof(string);
  74. dc.ColumnName = col.ToString();
  75. dt.Columns.Add(dc);
  76. col++;
  77. }
  78. for (int iRow = ; iRow <= rowcount; iRow++)
  79. {
  80. var dr = dt.NewRow();
  81. for (int iCol = ; iCol <= colcount; iCol++)
  82. {
  83. range = psheet.Cells[iRow, iCol] as Range;
  84. string content = "";
  85. if (range.Value != null)
  86. {
  87. content = range.Value.ToString();
  88. }
  89. dr[iCol - ] = content;
  90. }
  91. dt.Rows.Add(dr);
  92. }
  93. return dt;
  94.  
  95. }
  96. /// <summary>
  97. /// 导出excel
  98. /// </summary>
  99. /// <param name="table"></param>
  100. /// <param name="filename"></param>
  101. public void Datatabletoexcel(string filename, params SDataTable[] tables)
  102. {
  103. excel.DefaultFilePath = "";
  104. excel.DisplayAlerts = true;
  105. excel.SheetsInNewWorkbook = ;
  106. var book = excel.Workbooks.Add(true);
  107. foreach (var table in tables)
  108. {
  109. var result = book.Worksheets.Add();
  110. var sheet=book.ActiveSheet;
  111. sheet.Name = table.TableName;
  112. int rownum = table.Rows.Count;
  113. int colnum = table.Columns.Count;
  114. int rowindex = ;
  115. int columnindex = ;
  116. int row = ;
  117. int col = ;
  118. for (int i = ; i < rownum; i++)
  119. {
  120. col = ;
  121. for (int j = ; j < colnum; j++)
  122. {
  123. sheet.Cells[row + , col + ] = table.Rows[i][j] == null ? "" : table.Rows[i][j].ToString();
  124. col++;
  125. }
  126. row++;
  127. }
  128. #region//合并单元格
  129. //Range rangeLecture = sheet.Range[sheet.Cells[1, 1], sheet.Cells[2, 1]];//左上和右下
  130. //rangeLecture.MergeCells = true;
  131.  
  132. #endregion
  133. }
  134. excel.DisplayAlerts = false;
  135. book.SaveAs(filename);
  136. book.Close();
  137. System.Runtime.InteropServices.Marshal.ReleaseComObject(book);
  138. book = null;
  139. GC.Collect();
  140. GC.WaitForPendingFinalizers();
  141. }
  142. /// <summary>设置字体
  143. /// </summary>
  144. /// <param name="sheet"></param>
  145. void SetFont(Worksheet sheet)
  146. {
  147. excel.StandardFont = "宋体";
  148. excel.StandardFontSize = ;
  149. //sheet.Range.AutoFit();//自适应
  150. //sheet.Range[sheet.Cells[1, 1], sheet.Cells[4, 27]].HorizontalAlignment = Microsoft.Office.Interop.Excel.XlVAlign.xlVAlignCenter;//居中对齐
  151. //sheet.Range[sheet.Cells[1, 1], sheet.Cells[rowindex, 27]].Borders.LineStyle = 1;//设置边框
  152.  
  153. }
  154.  
  155. }

用NPOI 读写excel,速度比com快

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NPOI.HSSF;
using NPOI.HSSF.UserModel;
using System.IO;
using NPOI.SS.UserModel;
using System.Data;

  1.  
  2. public class NExcel
  3. {
  4. private HSSFWorkbook hssfworkbook;
  5. private string filepath;
  6.  
  7. public void Open(string file)
  8. {
  9. using (FileStream fs = new FileStream(file, FileMode.Open, FileAccess.Read))
  10. {
  11. hssfworkbook = new HSSFWorkbook(fs);
  12. }
  13. }
  14. /// <summary>
  15. /// 获取sheet
  16. /// </summary>
  17. /// <param name="index"></param>
  18. /// <param name="sheetname"></param>
  19. /// <returns></returns>
  20. public ISheet getSheet(int index,string sheetname=null)
  21. {
  22. if(hssfworkbook==null)return null;
  23. ISheet sheet;
  24. if(sheetname==null)
  25. {
  26. sheet =hssfworkbook.GetSheetAt(index);
  27. }else
  28. {
  29. sheet=hssfworkbook.GetSheet(sheetname);
  30. }
  31. return sheet;
  32.  
  33. }
  34. /// <summary>
  35. /// 读取excel文件
  36. /// </summary>
  37. /// <param name="sheet"></param>
  38. /// <returns></returns>
  39. public DataTable getData(ISheet sheet)
  40. {
  41. System.Collections.IEnumerator rows = sheet.GetRowEnumerator();
  42. DataTable dt = new DataTable();
  43. for (int j = ; j < (sheet.GetRow().LastCellNum); j++)
  44. {
  45. dt.Columns.Add(Convert.ToChar(((int)'A') + j).ToString());
  46. }
  47. while (rows.MoveNext())
  48. {
  49. if (rows.Current == null) continue ;
  50. HSSFRow row = (HSSFRow)rows.Current;
  51. DataRow dr = dt.NewRow();
  52. for (int i = ; i < row.LastCellNum-; i++)
  53. {
  54. var cell = row.GetCell(i);
  55. if (cell != null) cell.SetCellType(CellType.String);
  56. dr[i] = cell == null ? null : cell.ToString();
  57.  
  58. }
  59. dt.Rows.Add(dr);
  60. }
  61. return dt;
  62. }
  63.  
  64. /// <summary>
  65. /// 写excel文件
  66. /// </summary>
  67. /// <param name="filePath"></param>
  68. /// <param name="dts"></param>
  69. public void WriteExcel( string filePath,params DataTable[] dts)
  70. {
  71. if (string.IsNullOrEmpty(filePath)) return;
  72. NPOI.HSSF.UserModel.HSSFWorkbook book = new NPOI.HSSF.UserModel.HSSFWorkbook();
  73. foreach (var dt in dts)
  74. {
  75. if (null == dt && dt.Rows.Count==)continue;
  76. NPOI.SS.UserModel.ISheet sheet = book.CreateSheet(dt.TableName);
  77. NPOI.SS.UserModel.IRow row = sheet.CreateRow();
  78. for (int i = ; i < dt.Columns.Count; i++)
  79. {
  80. row.CreateCell(i).SetCellValue(dt.Columns[i].ColumnName);
  81. }
  82. for (int i = ; i < dt.Rows.Count; i++)
  83. {
  84. NPOI.SS.UserModel.IRow row2 = sheet.CreateRow(i + );
  85. for (int j = ; j < dt.Columns.Count; j++)
  86. {
  87. row2.CreateCell(j).SetCellValue(Convert.ToString(dt.Rows[i][j]));
  88. }
  89. }
  90. }
  91. // 写入到客户端
  92. using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
  93. {
  94. book.Write(ms);
  95. using (FileStream fs = new FileStream(filePath, FileMode.Create, FileAccess.Write))
  96. {
  97. byte[] data = ms.ToArray();
  98. fs.Write(data, , data.Length);
  99. fs.Flush();
  100. }
  101. book = null;
  102. }
  103. }
  104.  
  105. }

读写word 调用com

  1.  

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Office.Interop.Word;
using MSWord = Microsoft.Office.Interop.Word;

  1.  
  2. public class CSWord
  3. {
  4. private Application wordApp = null;
  5. private Document wordDoc = null;
  6. private string docPath = null;
  7. private object Nothing = System.Reflection.Missing.Value;
  8. public CSWord(string path,bool isOpen)
  9. {
  10. try
  11. {
  12. docPath = path;
  13. Object Nothing = System.Reflection.Missing.Value;
  14. //创建Word文档
  15. if (isOpen)
  16. {
  17. wordApp = new MSWord.Application();
  18. wordDoc = wordApp.Documents.Open(path);
  19. }
  20. else
  21. {
  22. wordApp = new MSWord.Application();
  23. wordDoc = wordApp.Documents.Add(ref Nothing, ref Nothing, ref Nothing, ref Nothing);
  24. }
  25. wordApp.Visible = false;
  26. }
  27. catch {
  28. throw new Exception("创建word对象失败");
  29. }
  30. }
  31.  
  32. public void SetFont()
  33. {
  34. wordApp.Selection.Font.Bold = ;
  35. wordApp.Selection.Font.Italic = ;
  36. wordApp.Selection.Font.Subscript = ;
  37.  
  38. }
  39. public void SetFontName(string strType)
  40. {
  41. wordApp.Selection.Font.Name = strType;
  42.  
  43. }
  44. public void SetFontSize(int nSize)
  45. {
  46. wordApp.Selection.Font.Size = nSize;
  47. }
  48. public void SetAlignment(WdParagraphAlignment align)
  49. {
  50. wordApp.Selection.ParagraphFormat.Alignment = align;
  51. }
  52. public void GoToTheEnd()
  53. {
  54. object unit;
  55. unit = Microsoft.Office.Interop.Word.WdUnits.wdStory;
  56. wordApp.Selection.EndKey(ref unit, ref Nothing);
  57.  
  58. }
  59. public void GoToTheBeginning()
  60. {
  61. object unit;
  62. unit = Microsoft.Office.Interop.Word.WdUnits.wdStory;
  63. wordApp.Selection.HomeKey(ref unit, ref Nothing);
  64.  
  65. }
  66.  
  67. /// <summary>
  68. /// 添加文字
  69. /// </summary>
  70. /// <param name="txtContent"></param>
  71. /// <param name="Bold"></param>
  72. /// <param name="size"></param>
  73. public void AddText(string txtContent,int Bold=,int size=)
  74. {
  75. //wordApp.Selection.Font.Spacing = 10;//字符间隔
  76.  
  77. wordApp.Selection.Font.Bold = Bold;
  78. wordApp.Selection.Font.Size = size;
  79. wordApp.Selection.TypeText(txtContent);
  80. wordApp.Selection.TypeParagraph();
  81. }
  82. /// <summary>
  83. /// 添加图片
  84. /// </summary>
  85. /// <param name="filepath"></param>
  86. public void AddPic(string filepath)
  87. {
  88. object range = wordDoc.Paragraphs.Last.Range;
  89. //定义该图片是否为外s部链接
  90. object linkToFile = false;//默认
  91. //定义插入的图片是否随word一起保存
  92. object saveWithDocument = true;
  93. //向word中写入图片
  94. wordDoc.InlineShapes.AddPicture(filepath, ref Nothing, ref Nothing, ref Nothing);
  95.  
  96. object unite = Microsoft.Office.Interop.Word.WdUnits.wdStory;
  97. wordApp.Selection.ParagraphFormat.Alignment = MSWord.WdParagraphAlignment.wdAlignParagraphCenter;//居中显示图片
  98. //wordDoc.InlineShapes[1].Height = 130;
  99. //wordDoc.InlineShapes[1].Width = 200;
  100. wordDoc.Content.InsertAfter("\n");
  101. wordApp.Selection.EndKey(ref unite, ref Nothing);
  102. wordApp.Selection.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter;
  103. wordApp.Selection.Font.Size = ;//字体大小
  104. wordApp.Selection.TypeText("图1 测试图片\n");
  105.  
  106. }
  107. /// <summary>
  108. /// 添加表
  109. /// </summary>
  110. public void AddTable()
  111. {
  112.  
  113. int tableRow = ;
  114. int tableColumn = ;
  115. //定义一个word中的表格对象
  116. MSWord.Table table = wordDoc.Tables.Add(wordApp.Selection.Range, tableRow, tableColumn, ref Nothing, ref Nothing);
  117. wordDoc.Tables[].Cell(, ).Range.Text = "列\n行";
  118. for (int i = ; i < tableRow; i++)
  119. {
  120. for (int j = ; j < tableColumn; j++)
  121. {
  122. if (i == )
  123. {
  124. table.Cell(i, j + ).Range.Text = "Column " + j;
  125. }
  126. if (j == )
  127. {
  128. table.Cell(i + , j).Range.Text = "Row " + i;
  129. }
  130. table.Cell(i + , j + ).Range.Text = i + "行 " + j + "列";
  131. }
  132. }
  133.  
  134. //添加行
  135. table.Rows.Add(ref Nothing);
  136. table.Rows[tableRow + ].Height = ;
  137. //向新添加的行的单元格中添加图片
  138. //string FileName = "d:\\kk.jpg";//图片所在路径
  139. object LinkToFile = false;
  140. object SaveWithDocument = true;
  141. object Anchor = table.Cell(tableRow + , tableColumn).Range;//选中要添加图片的单元格
  142. //wordDoc.Application.ActiveDocument.InlineShapes.AddPicture(FileName, ref LinkToFile, ref SaveWithDocument, ref Anchor);
  143. //wordDoc.Application.ActiveDocument.InlineShapes[1].Width = 75;//图片宽度
  144. //wordDoc.Application.ActiveDocument.InlineShapes[1].Height = 45;//图片高度
  145. // 将图片设置为四周环绕型
  146. //MSWord.Shape s = wordDoc.Application.ActiveDocument.InlineShapes[1].ConvertToShape();
  147. //s.WrapFormat.Type = MSWord.WdWrapType.wdWrapSquare;
  148. //设置table样式
  149. table.Rows.HeightRule = MSWord.WdRowHeightRule.wdRowHeightAtLeast;
  150. table.Rows.Height = wordApp.CentimetersToPoints(float.Parse("0.8"));
  151.  
  152. table.Range.Font.Size = 10.5F;
  153. table.Range.Font.Bold = ;
  154.  
  155. table.Range.ParagraphFormat.Alignment = MSWord.WdParagraphAlignment.wdAlignParagraphCenter;
  156. table.Range.Cells.VerticalAlignment = MSWord.WdCellVerticalAlignment.wdCellAlignVerticalBottom;
  157. //设置table边框样式
  158. table.Borders.OutsideLineStyle = MSWord.WdLineStyle.wdLineStyleDouble;
  159. table.Borders.InsideLineStyle = MSWord.WdLineStyle.wdLineStyleSingle;
  160.  
  161. table.Rows[].Range.Font.Bold = ;
  162. table.Rows[].Range.Font.Size = 12F;
  163. table.Cell(, ).Range.Font.Size = 10.5F;
  164. wordApp.Selection.Cells.Height = ;//所有单元格的高度
  165. for (int i = ; i <= tableRow; i++)
  166. {
  167. table.Rows[i].Height = ;
  168. }
  169. table.Cell(, ).Range.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphRight;
  170. table.Cell(, ).Range.Paragraphs[].Format.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphLeft;
  171.  
  172. table.Columns[].Width = ;
  173. for (int i = ; i <= tableColumn; i++)
  174. {
  175. table.Columns[i].Width = ;
  176. }
  177.  
  178. //添加表头斜线,并设置表头的样式
  179. table.Cell(, ).Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderDiagonalDown].Visible = true;
  180. table.Cell(, ).Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderDiagonalDown].Color = Microsoft.Office.Interop.Word.WdColor.wdColorGray60;
  181. table.Cell(, ).Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderDiagonalDown].LineWidth = Microsoft.Office.Interop.Word.WdLineWidth.wdLineWidth050pt;
  182.  
  183. //表格边框
  184. //表格内容行边框
  185. SetTableBorderStyle(table, MSWord.WdBorderType.wdBorderHorizontal, MSWord.WdColor.wdColorGray20, MSWord.WdLineWidth.wdLineWidth025pt);
  186. //表格内容列边框
  187. SetTableBorderStyle(table, MSWord.WdBorderType.wdBorderVertical, MSWord.WdColor.wdColorGray20, MSWord.WdLineWidth.wdLineWidth025pt);
  188. SetTableBorderStyle(table, MSWord.WdBorderType.wdBorderLeft, MSWord.WdColor.wdColorGray50, MSWord.WdLineWidth.wdLineWidth050pt);
  189. SetTableBorderStyle(table, MSWord.WdBorderType.wdBorderRight, MSWord.WdColor.wdColorGray50, MSWord.WdLineWidth.wdLineWidth050pt);
  190. SetTableBorderStyle(table, MSWord.WdBorderType.wdBorderTop, MSWord.WdColor.wdColorGray50, MSWord.WdLineWidth.wdLineWidth050pt);
  191. SetTableBorderStyle(table, MSWord.WdBorderType.wdBorderBottom, MSWord.WdColor.wdColorGray50, MSWord.WdLineWidth.wdLineWidth050pt);
  192. //合并单元格
  193. table.Cell(, ).Merge(table.Cell(, ));//横向合并
  194. table.Cell(, ).Merge(table.Cell(, ));//纵向合并
  195.  
  196. }
  197. public void OpenModel(string modelPath)
  198. {
  199. object ModelName = modelPath;
  200. wordDoc = wordApp.Documents.Open(ref ModelName);//打开word模板
  201. //下面操作模板。。。。
  202.  
  203. }
  204.  
  205. private void SetTableBorderStyle(Table table1,MSWord.WdBorderType bdType,MSWord.WdColor color,MSWord.WdLineWidth width)
  206. {
  207. table1.Borders[bdType].Visible = true;
  208. table1.Borders[bdType].Color = color;
  209. table1.Borders[bdType].LineWidth = width;
  210. }
  211. /// <summary>
  212. /// 保存
  213. /// </summary>
  214. /// <returns></returns>
  215. public bool Save()
  216. {
  217. try
  218. {
  219. object path = docPath;
  220. object format = MSWord.WdSaveFormat.wdFormatDocument;
  221.  
  222. wordDoc.SaveAs(ref path, ref format);
  223. wordDoc.Close(ref Nothing, ref Nothing, ref Nothing);
  224. wordApp.Quit(ref Nothing, ref Nothing, ref Nothing);
  225. return true;
  226. }
  227. catch
  228. {
  229. return false;
  230. }
  231. }
  232. /// <summary>
  233. /// 替换
  234. /// </summary>
  235. /// <param name="strOldText"></param>
  236. /// <param name="strNewText"></param>
  237. public void Replace(string strOldText, string strNewText)
  238. {
  239.  
  240. this.wordApp.Selection.Find.ClearFormatting();//移除Find的搜索文本和段落格式设置
  241. wordApp.Selection.Find.Text = strOldText;//需要查找的字符
  242. if (wordApp.Selection.Find.Execute())//查找字符
  243. {
  244. wordApp.Selection.TypeText(strNewText);//在找到的字符区域写数据
  245. }
  246.  
  247. }
  248.  
  249. /// <summary>
  250. ///查找字符
  251. /// </summary>
  252. /// <returns></returns>
  253. public bool FindStr(string str)
  254. {
  255. Find find = wordApp.Selection.Find;
  256. Object findText;
  257. Object matchCase = Type.Missing;
  258. Object matchWholeWord = Type.Missing;
  259. Object matchWildcards = Type.Missing;
  260. Object matchSoundsLike = Type.Missing;
  261. Object matchAllWordForms = Type.Missing;
  262. Object forward = true;
  263. Object wrap = WdFindWrap.wdFindStop;
  264. Object format = Type.Missing;
  265. Object replaceWith = Type.Missing;
  266. Object replace = Type.Missing;
  267. Object matchKashida = Type.Missing;
  268. Object matchDiacritics = Type.Missing;
  269. Object matchAlefHamza = Type.Missing;
  270. Object matchControl = Type.Missing;
  271.  
  272. if ((str == "") || (str == string.Empty))
  273. findText = find.Text;
  274. else
  275. findText = str;
  276. find.ClearFormatting();
  277. return find.Execute(ref findText, ref matchCase, ref matchWholeWord,
  278. ref matchWildcards, ref matchSoundsLike, ref matchAllWordForms,
  279. ref forward, ref wrap, ref format, ref replaceWith, ref replace,
  280. ref matchKashida, ref matchDiacritics, ref matchAlefHamza,
  281. ref matchControl);
  282. }
  283.  
  284. /// <summary>
  285. /// 保存成HTML
  286. /// </summary>
  287. /// <param name="strFileName"></param>
  288. public void SaveAsHtml(string strFileName)
  289. {
  290. Type wordType = wordApp.GetType();
  291. object missing = System.Reflection.Missing.Value;
  292. object fileName = strFileName;
  293. object Format = (int)Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatHTML;
  294. wordDoc.SaveAs(ref fileName, ref Format, ref missing, ref missing, ref missing, ref missing, ref missing,
  295. ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing);
  296.  
  297. }
  298.  
  299. public void Dispose()
  300. {
  301. if (wordDoc != null)
  302. {
  303. wordDoc.Close();
  304. }
  305. if (wordApp != null)
  306. {
  307. wordApp.Quit();
  308. }
  309. }
  310.  
  311. private void test()
  312. {
  313. Paragraphs pgs = wordApp.Selection.Paragraphs;
  314. foreach (Paragraph pg in pgs)
  315. {
  316. Console.WriteLine(pg.Range.Text);
  317. }
  318. }
  319. }

读写access ,调用OleDb

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Data.OleDb;
  6. using System.IO;
  7. using System.Data;
  8.  
  9. namespace CSharpTest
  10. {
  11. public class CAccessClass
  12. {
  13. private OleDbConnection DbConnection;
  14. private const string connect = "provider=microsoft.jet.oledb.4.0;Data Source=";
  15. private static void log(string msg)
  16. {
  17. using (StreamWriter sw = new StreamWriter("log.txt", true))
  18. {
  19. sw.WriteLine(String.Format("{0}:{1}", DateTime.Now.ToString(), msg));
  20.  
  21. }
  22.  
  23. }
  24.  
  25. public CAccessClass(string Path)
  26. {
  27. DbConnection = new OleDbConnection(connect + Path);
  28. }
  29. public DataTable SelectData(string sql)
  30. {
  31. try
  32. {
  33. DbConnection.Open();
  34. var myadapter = new OleDbDataAdapter();
  35. myadapter.SelectCommand = new OleDbCommand(sql, DbConnection);
  36. DataSet ds = new DataSet();
  37. myadapter.Fill(ds);
  38. return ds.Tables[];
  39. }
  40. catch (Exception ex)
  41. {
  42. return null;
  43.  
  44. }
  45. finally
  46. {
  47. DbConnection.Close();
  48. }
  49.  
  50. }
  51.  
  52. public int Delete(string sql)
  53. {
  54. try
  55. {
  56. DbConnection.Open();
  57. var cmd = new OleDbCommand(sql, DbConnection);
  58. return cmd.ExecuteNonQuery();
  59.  
  60. }
  61. catch (Exception ex)
  62. {
  63. return ;
  64. }
  65. finally
  66. {
  67. DbConnection.Close();
  68. }
  69.  
  70. }
  71.  
  72. public static void Test(string path=null)
  73. {
  74. if(path==null) path = @"D:\WORK\Project\苗尾\BGKDB.MDB";
  75. CAccessClass cac = new CAccessClass(path);
  76. string sql = "select * from Sensor where SensorType='钢筋计'";
  77. var table = cac.SelectData(sql);
  78. for (int i = ; i < table.Rows.Count; i++)
  79. {
  80. for (int j = ; j < table.Columns.Count; j++)
  81. {
  82. Console.Write(table.Rows[i][j]+" ");
  83. }
  84. Console.WriteLine();
  85. }
  86.  
  87. Console.WriteLine(String.Format("获取到{0}条数据", table.Rows.Count));
  88.  
  89. }
  90.  
  91. }
  92. }

上边调用com接口写法不够优雅,这里有动态类型写,会好看点

获取office程序的com对象:

  1. dynamic GetActiveObject(string key)
  2. {
  3. try
  4. {
  5. dynamic app = System.Runtime.InteropServices.Marshal.GetActiveObject(key);
  6. if (app != null)
  7. return app;
  8. }
  9. catch
  10. { }
  11. return null;
  12. }
    //这里是获取已经打开的office实例,如果没有运行的office实例,可以直接创建
    //key可以上上边的progid也可以是CLSID

//var type = Type.GetTypeFromProgID(key);
//app = Activator.CreateInstance(type);

  1.  

key是程序注册的prog,ms对应microsoft ,ki对应wps

  1. const string msWord = "Word.Application";
  2. const string kiWord = "KWPS.Application";
  3. const string msExcel = "Excel.Application";
  4. const string kiExcel = "KET.Application";
  5. const string msPPT = "PowerPoint.Application";
  6. const string kiPPT = "KWPP.Application";

因为两家的com对象接口基本一样·所以换下key基本就可以两家通用了

打开word写内容:

instance 是上边构造的对象,这里是在word最后加一行内容

  1. void WriteWord(dynamic instance,string path)
  2. {
  3. dynamic word = instance;
  4. try
  5. {
  6. word.Visible = true;
  7. dynamic documents = word.Documents;
  8. dynamic doc = documents.Open(path);
  9. dynamic lr = doc.Paragraphs.Last.Range;
  10. var msg = string.Format("这是添加一行数据{0}", DateTime.Now.ToString()) + Environment.NewLine;
  11. Console.WriteLine(msg);
  12. lr.Text += msg;
  13. doc.Close(-);
  14. word.Quit();
  15. }
  16. catch (Exception ex)
  17. {
  18. Console.WriteLine(string.Format("err:{0},{1}", ex.Message, ex.StackTrace));
  19. monitor.Set();
  20. }
  21. }

打开excel写内容,这里是在第一列的最后一行加一行数据

  1. void WriteExcel(dynamic instance, string path)
  2. {
  3. dynamic excel = instance;
  4. try
  5. {
  6. excel.Visible = true;
  7. dynamic books = excel.Workbooks;
  8. dynamic book = books.Open(path);
  9. dynamic sheet = book.Sheets();
  10. var row = sheet.UsedRange.Rows.Count + ;
  11. var msg = string.Format("这是添加一行数据{0}", DateTime.Now.ToString()) + Environment.NewLine;
  12. var range = sheet.Cells[row, ];
  13. range.Activate();
  14. range.Value = msg;
  15. Console.WriteLine(msg);
  16. Thread.Sleep();
  17. book.Close(-);
  18. excel.Quit();
  19. }
  20. catch (Exception ex)
  21. {
  22. Console.WriteLine(string.Format("err:{0},{1}", ex.Message, ex.StackTrace));
  23. monitor.Set();
  24. }
  25. }

ppt

  1. dynamic ppt = instance;
  2. try
  3. {
  4. ppt.Visible = true;
  5. dynamic Presentations = ppt.Presentations;
  6. dynamic Presentation = Presentations.Open(path);
  7. var msg = string.Format("这是添加一页数据{0}", DateTime.Now.ToString()) + Environment.NewLine;
  8. var Slides = Presentation.Slides;
  9. var cnt = Presentation.Slides.Count;
  10. dynamic layout;
  11. if (cnt != )
  12. {
  13. layout = Slides[cnt].CustomLayout;
  14. }
  15. else
  16. {
  17. var Master = Presentation.SlideMaster;
  18. layout = Master.CustomLayouts();
  19. }
  20. AsyncAppend(cnt.ToString());
  21. var sl = Slides.AddSlide(cnt + , layout);
  22. sl.Select();
  23. var shapes = sl.Shapes;
  24. dynamic title;
  25. title = shapes.Title;
  26. if(title==null)
  27. title = shapes.AddTitle();
  28. title.TextFrame.TextRange.Text = msg;
  29.  
  30. AsyncAppend(msg);
  31. Presentation.Save();
  32. Presentation.Close();
  33. if(chkQuit.Checked)
  34. {
  35. ppt.Quit();
  36. }
  37.  
  38. Thread.Sleep();
  39. }
  40. catch (Exception ex)
  41. {
  42. AsyncAppend(string.Format("err:{0},{1}", ex.Message, ex.StackTrace));
  43. monitor.Set();
  44. }

C# 读写xml、excel、word、ppt、access的更多相关文章

  1. Aspose 强大的服务器端 excel word ppt pdf 处理工具

    Aspose 强大的服务器端 excel word ppt pdf 处理工具 http://www.aspose.com/java/word-component.aspx

  2. Aspose office (Excel,Word,PPT),PDF 在线预览

    前文: 做个备份,拿的是试用版的 Aspose,功能见标题 代码: /// <summary> /// Aspose office (Excel,Word,PPT),PDF 在线预览 // ...

  3. excel,word,ppt,pdf,swf 文件互相转换

    转自:  http://www.cnblogs.com/wolf-sun/p/3569960.html 引言 之前项目需要,查找了office文档在线预览的解决方案,顺便记录一下,方便以后查询. 方案 ...

  4. Excel&&word&&PPT

    1. Excel 1.1 制作下拉框 选中单元格或列--> 菜单"数据" --> "数据验证"-->"设置" --> ...

  5. Spire.Office for .NET(Word、Excel、PPT、PDF等)

    使用Spire.Office for .NET(Word.Excel.PPT.PDF等)的初步感受 前言 本文大部分内容来自http://www.codeproject.com/Articles/71 ...

  6. Android遍历获取Office格式(Word,Excel,PPT,PDF)的文件并打开

    此案例主要是模仿QQ加载WPS(Word,Excel,PPT)本地文件可打开查看,使用ListView加载,使用线程扫描SD卡下所有目录加载指定的Word,Excel,PPT等格式的文件,ListVi ...

  7. Jacob工具类使用文件互转服务 word转html html转excel word转pdf excel转pdf ppt转pdf

    前提条件  必须安装MS office 1.jdk使用jdk1.8 2.jacob.dll放在..\jdk1.8\jre\bin目录下 3.eclipse的jre版本要和jdk一致,window-&g ...

  8. java实现在线预览--poi实现word、excel、ppt转html

    java实现在线预览 - -之poi实现word.excel.ppt转html 简介 java实现在线预览功能是一个大家在工作中也许会遇到的需求,如果公司有钱,直接使用付费的第三方软件或者云在线预览服 ...

  9. java实现在线预览 - -之poi实现word、excel、ppt转html

    简介 java实现在线预览功能是一个大家在工作中也许会遇到的需求,如果公司有钱,直接使用付费的第三方软件或者云在线预览服务就可以了,例如永中office.office web 365(http://w ...

随机推荐

  1. django中ModelForm解决多表单组合显示问题

    一.多表单组合显示问题 在项目中用ModelForm生成页面时 当有多表单组合显示时,会显示全部的关联表单数据. 而在实际项目中可能会出现只想让用户选择部分数据,这时候这样的显示就有问题. 二.问题解 ...

  2. Spring核心--IOC&AOP

    Ioc(控制反转) 所谓的控制反转就是应用本身不负责依赖对象的创建及维护,依赖对象的创建及维护是由外部容器负责的.这样控制权就由应用转移到了外部容器,控制权的转移就是所谓反转. AOP(面向切面编程) ...

  3. UML之类图详解

    原文链接:https://www.cnblogs.com/xsyblogs/p/3404202.html 我们通过一个示例来了解UML类图的基本语法结构.画UML类图其实有专业的工具,像常用的Visi ...

  4. django 部署到Ubuntu安装MYSQL56

    阿里云 Ubuntu 14.04 安装mysql 5.6 1.升级apt-get sudo apt-get update 2. 安装mysql5.6版本 apt-get install mysql-s ...

  5. width:100%以什么为基准的测试

    起初是遇到这样一个问题:当盒模型设为box-sizing:border-box;(移动端上经常这么干).子盒子的width:100%,子盒子的width等于父盒子contend的长度还是condend ...

  6. [HAOI2007]理想的正方形 BZOJ1047 二维RMQ

    题目描述 有一个a*b的整数组成的矩阵,现请你从中找出一个n*n的正方形区域,使得该区域所有数中的最大值和最小值的差最小. 输入输出格式 输入格式: 第一行为3个整数,分别表示a,b,n的值 第二行至 ...

  7. sql update 代替游标写法

    update TB_AreaUserDevice_Relation set OrderID = t.r from TB_AreaUserDevice_Relation rel inner join ( ...

  8. Android ToggleButton(开关函数)与switch (开关按钮)

    1.ToggleButton (1)介绍 (2)组件形状 (3)xml文件设置 <?xml version="1.0" encoding="utf-8"? ...

  9. QDU_组队训练(AJFC)

    A - Pretty Matrix DreamGrid's birthday is coming. As his best friend, BaoBao is going to prepare a g ...

  10. UESTC - 621

    f[n]:sigma(i,n),i<n g[n]:sigmaf[i],i<=n #include<bits/stdc++.h> using namespace std; con ...