C# 读写xml、excel、word、ppt、access
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;
public static void GetAreaCodes(string path,out string[] areaCodes ,out string[] pointCodes)
{
if (File.Exists(path))
{
try
{
XmlDocument xml = new XmlDocument();
xml.LoadXml(path);
List<string> areas = new List<string>();
var areanode = xml.SelectSingleNode("areaRoot");
var elements = areanode.ChildNodes;
foreach (var element in elements)
{
areas.Add((element as XmlElement).InnerXml);
}
List<string> points = new List<string>();
var pointnode = xml.SelectSingleNode("pointRoot");
elements = areanode.ChildNodes;
foreach (var element in elements)
{
points.Add((element as XmlElement).InnerXml);
}
areaCodes = areas.ToArray();
pointCodes = points.ToArray();
}
catch
{
pointCodes = new[] { "GPS点", "建屋", "等级公路" };
areaCodes = new[] { "砖房", "阳台", "建屋", "地类界", "变电房" };
} }
else
{
pointCodes = new[] { "GPS点", "建屋", "等级公路" };
areaCodes = new[] { "砖房", "阳台", "建屋", "地类界", "变电房" };
} } public static void WriteAreaCodes(string path, string[] areaCodes, string[] pointCodes)
{
try
{
XmlDocument xml=new XmlDocument();
XmlDeclaration xmlDeclaration = xml.CreateXmlDeclaration("1.0", "utf-8","yes");
XmlNode Codes = xml.CreateElement("Codes");
xml.AppendChild(xmlDeclaration);
xml.AppendChild(Codes);
XmlNode areaRoot = xml.CreateElement("areaRoot");
foreach (var str in areaCodes)
{
XmlElement areaCode = xml.CreateElement("areaCode");
areaCode.InnerXml=str;
areaRoot.AppendChild(areaCode);
}
Codes.AppendChild(areaRoot);
XmlNode pointRoot = xml.CreateElement("pointRoot");
foreach (var str in pointCodes)
{
XmlElement pointCode = xml.CreateElement("pointCode");
pointCode.InnerXml=str;
pointRoot.AppendChild(pointCode);
}
Codes.AppendChild(pointRoot);
xml.Save(path); }
catch (Exception ex)
{
throw ex;
} }
读写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;
public class CExcel
{ private string filepath = "";
private Microsoft.Office.Interop.Excel.Application excel;
private Workbook workbook = null;
public CExcel()
{
excel = new Application();
excel.Visible = false;
excel.DisplayAlerts = false;
}
/// <summary>
/// 打开Excel文件
/// </summary>
/// <param name="filename">文件名</param>
public void OpenExcel(string filename)
{
workbook = excel.Application.Workbooks.Open(filename);
}
/// <summary>
/// 获取一个sheet
/// </summary>
/// <param name="index">sheet索引</param>
/// <param name="sheetname">sheet名,默认为空,为空以第一个参数为准,否则以名为准</param>
/// <returns>返回worksheet对象</returns>
public Worksheet GetSheet(int index,string sheetname=null)
{
if (workbook == null) return null;
var sheet = workbook.Worksheets.get_Item(index);
if (sheetname == null) return sheet;
foreach (var sh in workbook.Worksheets)
{
sheet = sh as Worksheet;
if (sheet.Name == sheetname) break;
}
return sheet; }
/// <summary>
/// 关闭workbook
/// </summary>
public void Closeworkbook()
{
if (workbook != null) workbook.Close();
}
/// <summary>
/// 释放excel对象
/// </summary>
public void Dispose()
{
excel.Quit();
}
/// <summary>
/// 读取一个sheet内容
/// </summary>
/// <param name="psheet"></param>
/// <param name="index"></param>
/// <returns></returns>
public SDataTable GetTableFromSheet(Worksheet psheet, int index = )
{
int rowcount = psheet.UsedRange.Cells.Rows.Count;
int colcount = psheet.UsedRange.Columns.Count;
Range range;
SDataTable dt = new SDataTable();
dt.TableName = psheet.Parent.Name + psheet.Name;
DataColumn dc;
int ColumnID = ;
int col = ;
while (col <= colcount)
{
dc = new DataColumn();
dc.DataType = typeof(string);
dc.ColumnName = col.ToString();
dt.Columns.Add(dc);
col++;
}
for (int iRow = ; iRow <= rowcount; iRow++)
{
var dr = dt.NewRow();
for (int iCol = ; iCol <= colcount; iCol++)
{
range = psheet.Cells[iRow, iCol] as Range;
string content = "";
if (range.Value != null)
{
content = range.Value.ToString();
}
dr[iCol - ] = content;
}
dt.Rows.Add(dr);
}
return dt; }
/// <summary>
/// 导出excel
/// </summary>
/// <param name="table"></param>
/// <param name="filename"></param>
public void Datatabletoexcel(string filename, params SDataTable[] tables)
{
excel.DefaultFilePath = "";
excel.DisplayAlerts = true;
excel.SheetsInNewWorkbook = ;
var book = excel.Workbooks.Add(true);
foreach (var table in tables)
{
var result = book.Worksheets.Add();
var sheet=book.ActiveSheet;
sheet.Name = table.TableName;
int rownum = table.Rows.Count;
int colnum = table.Columns.Count;
int rowindex = ;
int columnindex = ;
int row = ;
int col = ;
for (int i = ; i < rownum; i++)
{
col = ;
for (int j = ; j < colnum; j++)
{
sheet.Cells[row + , col + ] = table.Rows[i][j] == null ? "" : table.Rows[i][j].ToString();
col++;
}
row++;
}
#region//合并单元格
//Range rangeLecture = sheet.Range[sheet.Cells[1, 1], sheet.Cells[2, 1]];//左上和右下
//rangeLecture.MergeCells = true; #endregion
}
excel.DisplayAlerts = false;
book.SaveAs(filename);
book.Close();
System.Runtime.InteropServices.Marshal.ReleaseComObject(book);
book = null;
GC.Collect();
GC.WaitForPendingFinalizers();
}
/// <summary>设置字体
/// </summary>
/// <param name="sheet"></param>
void SetFont(Worksheet sheet)
{
excel.StandardFont = "宋体";
excel.StandardFontSize = ;
//sheet.Range.AutoFit();//自适应
//sheet.Range[sheet.Cells[1, 1], sheet.Cells[4, 27]].HorizontalAlignment = Microsoft.Office.Interop.Excel.XlVAlign.xlVAlignCenter;//居中对齐
//sheet.Range[sheet.Cells[1, 1], sheet.Cells[rowindex, 27]].Borders.LineStyle = 1;//设置边框 } }
用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;
public class NExcel
{
private HSSFWorkbook hssfworkbook;
private string filepath; public void Open(string file)
{
using (FileStream fs = new FileStream(file, FileMode.Open, FileAccess.Read))
{
hssfworkbook = new HSSFWorkbook(fs);
}
}
/// <summary>
/// 获取sheet
/// </summary>
/// <param name="index"></param>
/// <param name="sheetname"></param>
/// <returns></returns>
public ISheet getSheet(int index,string sheetname=null)
{
if(hssfworkbook==null)return null;
ISheet sheet;
if(sheetname==null)
{
sheet =hssfworkbook.GetSheetAt(index);
}else
{
sheet=hssfworkbook.GetSheet(sheetname);
}
return sheet; }
/// <summary>
/// 读取excel文件
/// </summary>
/// <param name="sheet"></param>
/// <returns></returns>
public DataTable getData(ISheet sheet)
{
System.Collections.IEnumerator rows = sheet.GetRowEnumerator();
DataTable dt = new DataTable();
for (int j = ; j < (sheet.GetRow().LastCellNum); j++)
{
dt.Columns.Add(Convert.ToChar(((int)'A') + j).ToString());
}
while (rows.MoveNext())
{
if (rows.Current == null) continue ;
HSSFRow row = (HSSFRow)rows.Current;
DataRow dr = dt.NewRow();
for (int i = ; i < row.LastCellNum-; i++)
{
var cell = row.GetCell(i);
if (cell != null) cell.SetCellType(CellType.String);
dr[i] = cell == null ? null : cell.ToString(); }
dt.Rows.Add(dr);
}
return dt;
} /// <summary>
/// 写excel文件
/// </summary>
/// <param name="filePath"></param>
/// <param name="dts"></param>
public void WriteExcel( string filePath,params DataTable[] dts)
{
if (string.IsNullOrEmpty(filePath)) return;
NPOI.HSSF.UserModel.HSSFWorkbook book = new NPOI.HSSF.UserModel.HSSFWorkbook();
foreach (var dt in dts)
{
if (null == dt && dt.Rows.Count==)continue;
NPOI.SS.UserModel.ISheet sheet = book.CreateSheet(dt.TableName);
NPOI.SS.UserModel.IRow row = sheet.CreateRow();
for (int i = ; i < dt.Columns.Count; i++)
{
row.CreateCell(i).SetCellValue(dt.Columns[i].ColumnName);
}
for (int i = ; i < dt.Rows.Count; i++)
{
NPOI.SS.UserModel.IRow row2 = sheet.CreateRow(i + );
for (int j = ; j < dt.Columns.Count; j++)
{
row2.CreateCell(j).SetCellValue(Convert.ToString(dt.Rows[i][j]));
}
}
}
// 写入到客户端
using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
{
book.Write(ms);
using (FileStream fs = new FileStream(filePath, FileMode.Create, FileAccess.Write))
{
byte[] data = ms.ToArray();
fs.Write(data, , data.Length);
fs.Flush();
}
book = null;
}
} }
读写word 调用com
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Office.Interop.Word;
using MSWord = Microsoft.Office.Interop.Word;
public class CSWord
{
private Application wordApp = null;
private Document wordDoc = null;
private string docPath = null;
private object Nothing = System.Reflection.Missing.Value;
public CSWord(string path,bool isOpen)
{
try
{
docPath = path;
Object Nothing = System.Reflection.Missing.Value;
//创建Word文档
if (isOpen)
{
wordApp = new MSWord.Application();
wordDoc = wordApp.Documents.Open(path);
}
else
{
wordApp = new MSWord.Application();
wordDoc = wordApp.Documents.Add(ref Nothing, ref Nothing, ref Nothing, ref Nothing);
}
wordApp.Visible = false;
}
catch {
throw new Exception("创建word对象失败");
}
} public void SetFont()
{
wordApp.Selection.Font.Bold = ;
wordApp.Selection.Font.Italic = ;
wordApp.Selection.Font.Subscript = ; }
public void SetFontName(string strType)
{
wordApp.Selection.Font.Name = strType; }
public void SetFontSize(int nSize)
{
wordApp.Selection.Font.Size = nSize;
}
public void SetAlignment(WdParagraphAlignment align)
{
wordApp.Selection.ParagraphFormat.Alignment = align;
}
public void GoToTheEnd()
{
object unit;
unit = Microsoft.Office.Interop.Word.WdUnits.wdStory;
wordApp.Selection.EndKey(ref unit, ref Nothing); }
public void GoToTheBeginning()
{
object unit;
unit = Microsoft.Office.Interop.Word.WdUnits.wdStory;
wordApp.Selection.HomeKey(ref unit, ref Nothing); } /// <summary>
/// 添加文字
/// </summary>
/// <param name="txtContent"></param>
/// <param name="Bold"></param>
/// <param name="size"></param>
public void AddText(string txtContent,int Bold=,int size=)
{
//wordApp.Selection.Font.Spacing = 10;//字符间隔 wordApp.Selection.Font.Bold = Bold;
wordApp.Selection.Font.Size = size;
wordApp.Selection.TypeText(txtContent);
wordApp.Selection.TypeParagraph();
}
/// <summary>
/// 添加图片
/// </summary>
/// <param name="filepath"></param>
public void AddPic(string filepath)
{
object range = wordDoc.Paragraphs.Last.Range;
//定义该图片是否为外s部链接
object linkToFile = false;//默认
//定义插入的图片是否随word一起保存
object saveWithDocument = true;
//向word中写入图片
wordDoc.InlineShapes.AddPicture(filepath, ref Nothing, ref Nothing, ref Nothing); object unite = Microsoft.Office.Interop.Word.WdUnits.wdStory;
wordApp.Selection.ParagraphFormat.Alignment = MSWord.WdParagraphAlignment.wdAlignParagraphCenter;//居中显示图片
//wordDoc.InlineShapes[1].Height = 130;
//wordDoc.InlineShapes[1].Width = 200;
wordDoc.Content.InsertAfter("\n");
wordApp.Selection.EndKey(ref unite, ref Nothing);
wordApp.Selection.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter;
wordApp.Selection.Font.Size = ;//字体大小
wordApp.Selection.TypeText("图1 测试图片\n"); }
/// <summary>
/// 添加表
/// </summary>
public void AddTable()
{ int tableRow = ;
int tableColumn = ;
//定义一个word中的表格对象
MSWord.Table table = wordDoc.Tables.Add(wordApp.Selection.Range, tableRow, tableColumn, ref Nothing, ref Nothing);
wordDoc.Tables[].Cell(, ).Range.Text = "列\n行";
for (int i = ; i < tableRow; i++)
{
for (int j = ; j < tableColumn; j++)
{
if (i == )
{
table.Cell(i, j + ).Range.Text = "Column " + j;
}
if (j == )
{
table.Cell(i + , j).Range.Text = "Row " + i;
}
table.Cell(i + , j + ).Range.Text = i + "行 " + j + "列";
}
} //添加行
table.Rows.Add(ref Nothing);
table.Rows[tableRow + ].Height = ;
//向新添加的行的单元格中添加图片
//string FileName = "d:\\kk.jpg";//图片所在路径
object LinkToFile = false;
object SaveWithDocument = true;
object Anchor = table.Cell(tableRow + , tableColumn).Range;//选中要添加图片的单元格
//wordDoc.Application.ActiveDocument.InlineShapes.AddPicture(FileName, ref LinkToFile, ref SaveWithDocument, ref Anchor);
//wordDoc.Application.ActiveDocument.InlineShapes[1].Width = 75;//图片宽度
//wordDoc.Application.ActiveDocument.InlineShapes[1].Height = 45;//图片高度
// 将图片设置为四周环绕型
//MSWord.Shape s = wordDoc.Application.ActiveDocument.InlineShapes[1].ConvertToShape();
//s.WrapFormat.Type = MSWord.WdWrapType.wdWrapSquare;
//设置table样式
table.Rows.HeightRule = MSWord.WdRowHeightRule.wdRowHeightAtLeast;
table.Rows.Height = wordApp.CentimetersToPoints(float.Parse("0.8")); table.Range.Font.Size = 10.5F;
table.Range.Font.Bold = ; table.Range.ParagraphFormat.Alignment = MSWord.WdParagraphAlignment.wdAlignParagraphCenter;
table.Range.Cells.VerticalAlignment = MSWord.WdCellVerticalAlignment.wdCellAlignVerticalBottom;
//设置table边框样式
table.Borders.OutsideLineStyle = MSWord.WdLineStyle.wdLineStyleDouble;
table.Borders.InsideLineStyle = MSWord.WdLineStyle.wdLineStyleSingle; table.Rows[].Range.Font.Bold = ;
table.Rows[].Range.Font.Size = 12F;
table.Cell(, ).Range.Font.Size = 10.5F;
wordApp.Selection.Cells.Height = ;//所有单元格的高度
for (int i = ; i <= tableRow; i++)
{
table.Rows[i].Height = ;
}
table.Cell(, ).Range.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphRight;
table.Cell(, ).Range.Paragraphs[].Format.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphLeft; table.Columns[].Width = ;
for (int i = ; i <= tableColumn; i++)
{
table.Columns[i].Width = ;
} //添加表头斜线,并设置表头的样式
table.Cell(, ).Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderDiagonalDown].Visible = true;
table.Cell(, ).Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderDiagonalDown].Color = Microsoft.Office.Interop.Word.WdColor.wdColorGray60;
table.Cell(, ).Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderDiagonalDown].LineWidth = Microsoft.Office.Interop.Word.WdLineWidth.wdLineWidth050pt; //表格边框
//表格内容行边框
SetTableBorderStyle(table, MSWord.WdBorderType.wdBorderHorizontal, MSWord.WdColor.wdColorGray20, MSWord.WdLineWidth.wdLineWidth025pt);
//表格内容列边框
SetTableBorderStyle(table, MSWord.WdBorderType.wdBorderVertical, MSWord.WdColor.wdColorGray20, MSWord.WdLineWidth.wdLineWidth025pt);
SetTableBorderStyle(table, MSWord.WdBorderType.wdBorderLeft, MSWord.WdColor.wdColorGray50, MSWord.WdLineWidth.wdLineWidth050pt);
SetTableBorderStyle(table, MSWord.WdBorderType.wdBorderRight, MSWord.WdColor.wdColorGray50, MSWord.WdLineWidth.wdLineWidth050pt);
SetTableBorderStyle(table, MSWord.WdBorderType.wdBorderTop, MSWord.WdColor.wdColorGray50, MSWord.WdLineWidth.wdLineWidth050pt);
SetTableBorderStyle(table, MSWord.WdBorderType.wdBorderBottom, MSWord.WdColor.wdColorGray50, MSWord.WdLineWidth.wdLineWidth050pt);
//合并单元格
table.Cell(, ).Merge(table.Cell(, ));//横向合并
table.Cell(, ).Merge(table.Cell(, ));//纵向合并 }
public void OpenModel(string modelPath)
{
object ModelName = modelPath;
wordDoc = wordApp.Documents.Open(ref ModelName);//打开word模板
//下面操作模板。。。。 } private void SetTableBorderStyle(Table table1,MSWord.WdBorderType bdType,MSWord.WdColor color,MSWord.WdLineWidth width)
{
table1.Borders[bdType].Visible = true;
table1.Borders[bdType].Color = color;
table1.Borders[bdType].LineWidth = width;
}
/// <summary>
/// 保存
/// </summary>
/// <returns></returns>
public bool Save()
{
try
{
object path = docPath;
object format = MSWord.WdSaveFormat.wdFormatDocument; wordDoc.SaveAs(ref path, ref format);
wordDoc.Close(ref Nothing, ref Nothing, ref Nothing);
wordApp.Quit(ref Nothing, ref Nothing, ref Nothing);
return true;
}
catch
{
return false;
}
}
/// <summary>
/// 替换
/// </summary>
/// <param name="strOldText"></param>
/// <param name="strNewText"></param>
public void Replace(string strOldText, string strNewText)
{ this.wordApp.Selection.Find.ClearFormatting();//移除Find的搜索文本和段落格式设置
wordApp.Selection.Find.Text = strOldText;//需要查找的字符
if (wordApp.Selection.Find.Execute())//查找字符
{
wordApp.Selection.TypeText(strNewText);//在找到的字符区域写数据
} } /// <summary>
///查找字符
/// </summary>
/// <returns></returns>
public bool FindStr(string str)
{
Find find = wordApp.Selection.Find;
Object findText;
Object matchCase = Type.Missing;
Object matchWholeWord = Type.Missing;
Object matchWildcards = Type.Missing;
Object matchSoundsLike = Type.Missing;
Object matchAllWordForms = Type.Missing;
Object forward = true;
Object wrap = WdFindWrap.wdFindStop;
Object format = Type.Missing;
Object replaceWith = Type.Missing;
Object replace = Type.Missing;
Object matchKashida = Type.Missing;
Object matchDiacritics = Type.Missing;
Object matchAlefHamza = Type.Missing;
Object matchControl = Type.Missing; if ((str == "") || (str == string.Empty))
findText = find.Text;
else
findText = str;
find.ClearFormatting();
return find.Execute(ref findText, ref matchCase, ref matchWholeWord,
ref matchWildcards, ref matchSoundsLike, ref matchAllWordForms,
ref forward, ref wrap, ref format, ref replaceWith, ref replace,
ref matchKashida, ref matchDiacritics, ref matchAlefHamza,
ref matchControl);
} /// <summary>
/// 保存成HTML
/// </summary>
/// <param name="strFileName"></param>
public void SaveAsHtml(string strFileName)
{
Type wordType = wordApp.GetType();
object missing = System.Reflection.Missing.Value;
object fileName = strFileName;
object Format = (int)Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatHTML;
wordDoc.SaveAs(ref fileName, ref Format, ref missing, ref missing, ref missing, ref missing, ref missing,
ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing); } public void Dispose()
{
if (wordDoc != null)
{
wordDoc.Close();
}
if (wordApp != null)
{
wordApp.Quit();
}
} private void test()
{
Paragraphs pgs = wordApp.Selection.Paragraphs;
foreach (Paragraph pg in pgs)
{
Console.WriteLine(pg.Range.Text);
}
}
}
读写access ,调用OleDb
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.OleDb;
using System.IO;
using System.Data; namespace CSharpTest
{
public class CAccessClass
{
private OleDbConnection DbConnection;
private const string connect = "provider=microsoft.jet.oledb.4.0;Data Source=";
private static void log(string msg)
{
using (StreamWriter sw = new StreamWriter("log.txt", true))
{
sw.WriteLine(String.Format("{0}:{1}", DateTime.Now.ToString(), msg)); } } public CAccessClass(string Path)
{
DbConnection = new OleDbConnection(connect + Path);
}
public DataTable SelectData(string sql)
{
try
{
DbConnection.Open();
var myadapter = new OleDbDataAdapter();
myadapter.SelectCommand = new OleDbCommand(sql, DbConnection);
DataSet ds = new DataSet();
myadapter.Fill(ds);
return ds.Tables[];
}
catch (Exception ex)
{
return null; }
finally
{
DbConnection.Close();
} } public int Delete(string sql)
{
try
{
DbConnection.Open();
var cmd = new OleDbCommand(sql, DbConnection);
return cmd.ExecuteNonQuery(); }
catch (Exception ex)
{
return ;
}
finally
{
DbConnection.Close();
} } public static void Test(string path=null)
{
if(path==null) path = @"D:\WORK\Project\苗尾\BGKDB.MDB";
CAccessClass cac = new CAccessClass(path);
string sql = "select * from Sensor where SensorType='钢筋计'";
var table = cac.SelectData(sql);
for (int i = ; i < table.Rows.Count; i++)
{
for (int j = ; j < table.Columns.Count; j++)
{
Console.Write(table.Rows[i][j]+" ");
}
Console.WriteLine();
} Console.WriteLine(String.Format("获取到{0}条数据", table.Rows.Count)); } }
}
上边调用com接口写法不够优雅,这里有动态类型写,会好看点
获取office程序的com对象:
dynamic GetActiveObject(string key)
{
try
{
dynamic app = System.Runtime.InteropServices.Marshal.GetActiveObject(key);
if (app != null)
return app;
}
catch
{ }
return null;
}
//这里是获取已经打开的office实例,如果没有运行的office实例,可以直接创建
//key可以上上边的progid也可以是CLSID
//var type = Type.GetTypeFromProgID(key);
//app = Activator.CreateInstance(type);
key是程序注册的prog,ms对应microsoft ,ki对应wps
const string msWord = "Word.Application";
const string kiWord = "KWPS.Application";
const string msExcel = "Excel.Application";
const string kiExcel = "KET.Application";
const string msPPT = "PowerPoint.Application";
const string kiPPT = "KWPP.Application";
因为两家的com对象接口基本一样·所以换下key基本就可以两家通用了
打开word写内容:
instance 是上边构造的对象,这里是在word最后加一行内容
void WriteWord(dynamic instance,string path)
{
dynamic word = instance;
try
{
word.Visible = true;
dynamic documents = word.Documents;
dynamic doc = documents.Open(path);
dynamic lr = doc.Paragraphs.Last.Range;
var msg = string.Format("这是添加一行数据{0}", DateTime.Now.ToString()) + Environment.NewLine;
Console.WriteLine(msg);
lr.Text += msg;
doc.Close(-);
word.Quit();
}
catch (Exception ex)
{
Console.WriteLine(string.Format("err:{0},{1}", ex.Message, ex.StackTrace));
monitor.Set();
}
}
打开excel写内容,这里是在第一列的最后一行加一行数据
void WriteExcel(dynamic instance, string path)
{
dynamic excel = instance;
try
{
excel.Visible = true;
dynamic books = excel.Workbooks;
dynamic book = books.Open(path);
dynamic sheet = book.Sheets();
var row = sheet.UsedRange.Rows.Count + ;
var msg = string.Format("这是添加一行数据{0}", DateTime.Now.ToString()) + Environment.NewLine;
var range = sheet.Cells[row, ];
range.Activate();
range.Value = msg;
Console.WriteLine(msg);
Thread.Sleep();
book.Close(-);
excel.Quit();
}
catch (Exception ex)
{
Console.WriteLine(string.Format("err:{0},{1}", ex.Message, ex.StackTrace));
monitor.Set();
}
}
ppt
dynamic ppt = instance;
try
{
ppt.Visible = true;
dynamic Presentations = ppt.Presentations;
dynamic Presentation = Presentations.Open(path);
var msg = string.Format("这是添加一页数据{0}", DateTime.Now.ToString()) + Environment.NewLine;
var Slides = Presentation.Slides;
var cnt = Presentation.Slides.Count;
dynamic layout;
if (cnt != )
{
layout = Slides[cnt].CustomLayout;
}
else
{
var Master = Presentation.SlideMaster;
layout = Master.CustomLayouts();
}
AsyncAppend(cnt.ToString());
var sl = Slides.AddSlide(cnt + , layout);
sl.Select();
var shapes = sl.Shapes;
dynamic title;
title = shapes.Title;
if(title==null)
title = shapes.AddTitle();
title.TextFrame.TextRange.Text = msg; AsyncAppend(msg);
Presentation.Save();
Presentation.Close();
if(chkQuit.Checked)
{
ppt.Quit();
} Thread.Sleep();
}
catch (Exception ex)
{
AsyncAppend(string.Format("err:{0},{1}", ex.Message, ex.StackTrace));
monitor.Set();
}
C# 读写xml、excel、word、ppt、access的更多相关文章
- Aspose 强大的服务器端 excel word ppt pdf 处理工具
Aspose 强大的服务器端 excel word ppt pdf 处理工具 http://www.aspose.com/java/word-component.aspx
- Aspose office (Excel,Word,PPT),PDF 在线预览
前文: 做个备份,拿的是试用版的 Aspose,功能见标题 代码: /// <summary> /// Aspose office (Excel,Word,PPT),PDF 在线预览 // ...
- excel,word,ppt,pdf,swf 文件互相转换
转自: http://www.cnblogs.com/wolf-sun/p/3569960.html 引言 之前项目需要,查找了office文档在线预览的解决方案,顺便记录一下,方便以后查询. 方案 ...
- Excel&&word&&PPT
1. Excel 1.1 制作下拉框 选中单元格或列--> 菜单"数据" --> "数据验证"-->"设置" --> ...
- Spire.Office for .NET(Word、Excel、PPT、PDF等)
使用Spire.Office for .NET(Word.Excel.PPT.PDF等)的初步感受 前言 本文大部分内容来自http://www.codeproject.com/Articles/71 ...
- Android遍历获取Office格式(Word,Excel,PPT,PDF)的文件并打开
此案例主要是模仿QQ加载WPS(Word,Excel,PPT)本地文件可打开查看,使用ListView加载,使用线程扫描SD卡下所有目录加载指定的Word,Excel,PPT等格式的文件,ListVi ...
- 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 ...
- java实现在线预览--poi实现word、excel、ppt转html
java实现在线预览 - -之poi实现word.excel.ppt转html 简介 java实现在线预览功能是一个大家在工作中也许会遇到的需求,如果公司有钱,直接使用付费的第三方软件或者云在线预览服 ...
- java实现在线预览 - -之poi实现word、excel、ppt转html
简介 java实现在线预览功能是一个大家在工作中也许会遇到的需求,如果公司有钱,直接使用付费的第三方软件或者云在线预览服务就可以了,例如永中office.office web 365(http://w ...
随机推荐
- [转载]ssget 用法详解 by yxp
总结得很好的ssget用法.....如此好文,必须转载. 原文地址: http://blog.csdn.net/yxp_xa/article/details/72229202 ssget 用法详解 b ...
- docker kubernetes swarm spring cloud结合学习资源
http://www.docin.com/p-2062732301.html https://blog.csdn.net/michael_hm/article/details/79213839 htt ...
- Sample-Code:Translator
<h2>My Spanish Translator</h2> <p> Enter your text in English: </p> <p&g ...
- 百度编辑器 Ueditor使用记录
Ueditor官网: http://fex.baidu.com/ueditor/#dev-bale_width_grunt UeditorAPI文档: https://ueditor.baidu.co ...
- MySQL事务及事务隔离级别 锁机制
什么是事务? 当多个用户访问同一份数据时,一个用户在更改数据的过程中可能有其他用户同时发起更改请求,为保证数据库记录的更新从一个一致性状态更改为另一个一致性状态,这样的操作过程就是事务.事务具有的AC ...
- Centos文章列表
1.Linux 中将用户添加到组的指令:https://cnzhx.net/blog/linux-add-user-to-group/ 2.CentOS7为firewalld添加开放端口及相关操作:h ...
- 绿色版NVM安装与配置详细说明
绿色版本(不需要安装,直接解压,然后配置环境变量等) 由于最初发布的nvm并不支持window,所以如果希望可以像在*nix上一样控制node的版本,有两种选择: nvm-windows nodi ...
- Android StateListDrawable资源的使用(文本的高亮显示)
1.介绍 2.xml文件属性介绍 3.实例演示 <1>新建drawable文件 app--->src---->main---->res---->drawable , ...
- 【原创】SpringMVC同一RequestMapping返回不同的类型
曾经在工作中遇到过导出文件时,需要根据不同情况返回不同的数据的情况. 例如: 如果没有数据,弹框提示"没有数据" 导出报错,弹框提示"系统错误" 正常情况下,下 ...
- POJ2449 Remmarguts' Date A*算法
题意是让求从st的ed第k短路... 考虑A*算法:先把终点到每个点最短路跑出来(注意要建反图),当做估价函数h(u),然后跑A* 每次取出总代价最小的,即g(u)+h(u)最小的进行扩展,注意如果u ...