一、word

这是我以前工作时写过的一个业务逻辑处理类,里面有不少文件操作的方法,这里主要关注一下C#对word的操作。里面的方法可以直接拿出来用,主要是通过word的dot模版来进行创建word、替换word等操作。

namespace Excel2Word
{
public class BLL
{
private Microsoft.Office.Interop.Word.Application app = null;//全局变量 word应用程序 /// <summary>
/// 从Excel中读取数据
/// </summary>
/// <param name="excelPath"></param>
/// <param name="sheetName"></param>
/// <returns></returns>
public static DataSet GetDataFromExcel(string excelPath, string sheetName)
{
DataSet ds = new DataSet();
string strConn = "Provider=Microsoft.Jet.OleDb.4.0; Data Source=" + excelPath.ToString().Trim() + "; Extended Properties=Excel 8.0;"; try
{
using (OleDbConnection conn = new OleDbConnection(strConn))
{
conn.Open(); OleDbDataAdapter oda = new OleDbDataAdapter("select * from [" + sheetName + "]", conn);
oda.Fill(ds);
}
}
catch
{
throw new Exception("获取Excel数据时发生异常...");
}
return ds;
} /// <summary>
/// Word文本替换
/// </summary>
/// <param name="doc">文档</param>
/// <param name="args">要替换的内容</param>
public void ReplaceWord(Document doc, Dictionary<string, string> args)
{
try
{
object first = 0;
object last = doc.Characters.Count;
Range range = doc.Range(ref first, ref last); Microsoft.Office.Interop.Word.Find finder = range.Find;
finder.ClearFormatting(); object missingValue = Type.Missing;
object replaceArea = Microsoft.Office.Interop.Word.WdReplace.wdReplaceAll; foreach (var item in args)
{
object findStr = "{" + item.Key.Trim() + "}";
object replaceStr = item.Value.Trim(); //替换内容
finder.Execute(ref findStr, ref missingValue, ref missingValue,
ref missingValue, ref missingValue, ref missingValue,
ref missingValue, ref missingValue, ref missingValue,
ref replaceStr, ref replaceArea, ref missingValue,
ref missingValue, ref missingValue, ref missingValue);
}
}
catch
{
return;
}
} /// <summary>
/// word文档资源释放
/// </summary>
/// <param name="doc">要释放资源的文档</param>
public void DisposeWord(Document doc)
{
try
{
object oMissing = System.Reflection.Missing.Value; if (doc != null)
{
//关闭Word并回收资源
doc.Close(ref oMissing, ref oMissing, ref oMissing);
System.Runtime.InteropServices.Marshal.ReleaseComObject(doc);
doc = null;
} if (app != null)
{
app.Quit(ref oMissing, ref oMissing, ref oMissing);
System.Runtime.InteropServices.Marshal.ReleaseComObject(app);
app = null;
GC.Collect();
}
}
catch
{
return;
}
} /// <summary>
/// 从模板创建Word文件
/// </summary>
/// <param name="fileName">模板位置及名称</param>
/// <returns></returns>
public Document CreateWord(string fileName, string dsr)
{
try
{
app = new Microsoft.Office.Interop.Word.Application();//打开word程序
Document doc = new Document();//创建word对象
object unknow = Type.Missing;
string date = DateTime.Now.ToShortDateString();
object savefilename = @"D:\" + dsr + ".doc";//保存路径
object File = fileName;
app.Visible = false;//设置word程序为不可见
doc = app.Documents.Open(ref File,
ref unknow, ref unknow, ref unknow, ref unknow, ref unknow,
ref unknow, ref unknow, ref unknow, ref unknow, ref unknow,
ref unknow, ref unknow, ref unknow, ref unknow, ref unknow);//打开word文档 doc.SaveAs(ref savefilename, ref unknow, ref unknow, ref unknow, ref unknow, ref unknow, ref unknow, ref unknow, ref unknow, ref unknow, ref unknow, ref unknow, ref unknow, ref unknow, ref unknow, ref unknow);//保存word文档 return doc;
}
catch
{
return null;
}
}
}
}

二、excel

webform中,导出excel的代码:

public void ExportResult(DataTable dt, string excelName) { Response.Clear(); Response.Charset = ""; Response.ContentType = "applicationnd.ms-xls"; StringWriter sw = new StringWriter(); HtmlTextWriter htmlWrite = new HtmlTextWriter(sw); DataGrid dg = new DataGrid(); dg.DataSource = dt; dg.DataBind(); dg.RenderControl(htmlWrite); Response.AddHeader("content-disposition", "attachment;filename=" + HttpUtility.UrlEncode(excelName)); Response.Write(sw.ToString()); Response.End(); }

如果遇到身份证等类型的字段,由于科学计数法的原因导出excel之后很可能会“截断”,因此有必要对这种长整型的字段进行处理。

/// <summary>
/// 过滤低位非打印字符
/// </summary>
/// <param name="tmp"></param>
/// <returns></returns>
private string ReplaceLowOrderASCIICharacters(string tmp)
{
StringBuilder info = new StringBuilder();
foreach (char cc in tmp)
{
int ss = (int)cc;
if (((ss >= 0) && (ss <= 8)) || ((ss >= 11) && (ss <= 12)) || ((ss >= 14) && (ss <= 32)))
info.AppendFormat(" ", ss);
else info.Append(cc);
}
return info.ToString();
}

winform中,客户端生成excel的代码:

前提是要安装office,原理是通过office进程生成excel文件。

/// <summary>
/// 从DataSet生成Excel
/// </summary>
/// <param name="ds">DataSet</param>
/// <param name="strExcelFileName">文件名</param>
public void ExportExcelByDataSet(DataSet ds, string strExcelFileName)
{
Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application(); int rowIndex = 1;
int colIndex = 0; excel.Application.Workbooks.Add(true); DataTable dt = ds.Tables[0];
foreach (DataColumn col in dt.Columns)
{
colIndex++;
excel.Cells[1, colIndex] = col.ColumnName;
} foreach (DataRow row in dt.Rows)
{
rowIndex++;
colIndex = 0; foreach (DataColumn col in dt.Columns)
{
colIndex++;
excel.Cells[rowIndex, colIndex] = row[col.ColumnName].ToString();
}
} excel.Visible = false;
excel.ActiveWorkbook.SaveAs(strExcelFileName + ".XLS", Microsoft.Office.Interop.Excel.XlFileFormat.xlExcel9795, null, null, false, false, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange, null, null, null, null, null); excel.Quit();
excel = null;
GC.Collect();
}

三、pdf

搜索《PDF文件制作全攻略》,可以找到现成的资料,里面的代码和文档也相对比较齐全、清晰,这里简单做个示例demo——生成一个带章节的,内容为图片的pdf文档。

实现步骤:

1)在vs环境下新建项目,引用 ICSharpCode.SharpZipLib.dll、itextsharp.dll 这两个dll文件

2)在按钮事件下输入如下代码:

//设置版面为A4大小
Document document = new Document(PageSize.A4); //创建一个test.pdf文件
PdfWriter.getInstance(document, new FileStream("test.pdf", FileMode.Create)); document.Open();//打开pdf文档 try
{
string[] images = Directory.GetFiles("test/"); for (int i = 0; i < images.Length; i++)
{
//定义章节
Chapter chapter = new Chapter(new Paragraph(images[i]), i + 1); //加入章节
document.Add(chapter); //获得图片
iTextSharp.text.Image tempImage = iTextSharp.text.Image.getInstance(images[i]); //设置图片大小为原图的70%
tempImage.scalePercent(70); //文档加入图片
document.Add(tempImage); //文档新建一页
document.newPage();
} }
catch (Exception ex)
{
throw ex;
}
document.Close();//关闭pdf文档

C#对word、excel、pdf等格式文件的操作总结的更多相关文章

  1. Word,Excel,pdf,txt等文件上传并提取内容

    近期项目需求:1.要用到各种文件上传,下载. 2.并对文件进行搜索. 3.仅仅要文件里包括有搜索的内容,所有显示出来. 今天正好有时间整理一下,方便以后阅读,及对须要用到的朋友提供微薄之力.首先在实现 ...

  2. 在线文档转换API word,excel,ppt等在线文件转pdf、png

    在线文档转换API提供word,excel,ppt等在线文件转pdf.png等,文档:https://www.juhe.cn/docs/api/id/259 接口地址:http://v.juhe.cn ...

  3. datatable导出到Word / Excel / PDF / HTML .NET

    原文发布时间为:2011-01-21 -- 来源于本人的百度文章 [由搬家工具导入] IEnumerable - DataTable Export to Word / Excel / PDF / HT ...

  4. word转pdf字体格式变乱的问题

    完成word转pdf的功能之后,本地测试没问题,然后发布到服务器上,就遇到了字体变乱的问题,如下: 由于我本地发布后导出没有出现同样情况,而服务器和本地的最大区别在于字体库,于是,把服务器上关于需要用 ...

  5. 2、Python djang 框架下的word Excel TXT Image 等文件的下载

    2.python实现文件下载 (1)方法一.直接用a标签的href+数据库中文件地址,即可下载.缺点:word excel是直接弹框下载,对于image txt 等文件的下载方式是直接在新页面打开. ...

  6. Web方式预览Office/Word/Excel/pdf文件解决方案

    最近在做项目时需要在Web端预览一些Office文件,经过在万能的互联网上一番搜索确定并解决了. 虽然其中碰到的一些问题已经通过搜索和自己研究解决了,但是觉得有必要将整个过程记录下来,以方便自己以后查 ...

  7. 将Excel另存为CSV格式文件

    直接将Excel另存为CSV,速度很快: $CurrentPath = $MyInvocation.MyCommand.Path.substring(0,$MyInvocation.MyCommand ...

  8. Excel和CSV格式文件的不同之处

    来源:https://blog.csdn.net/weixin_39198406/article/details/78705016 1.个人理解:为何选择使用csv来存储接口测试用例相关字段数据,而不 ...

  9. 如何把Excel另存为XML格式文件(快速转换)

    这时,我们尝试另存为另一种文件类型: XML电子表格2003(*.xml)

随机推荐

  1. 【49】了解new_handler的行为

    1.使用operator new无法获取内存时,对于旧式编译器,会返回一个null指针.对于新式编译器,会抛出一个异常. 2.考虑下面的需求,当operator new 无法获取内存时,程序员期望获得 ...

  2. SQL Sever——无法连接到(local)。“未配置远程连接”和“请求失败或服务未及时响应”

       攻克了上篇博客提到的"远程过程调用失败(0x800706be)"的问题. 新的问题接踵而至. . . 一.       watermark/2/text/aHR0cDovL2 ...

  3. WebStorm 6.0下运行pomelo项目

    最近想使用WebStorm来写pomelo,初次使用WebStorm,网上找了老半天根本没有介绍WebStorm如何创建或者打开运行pomelo的教程,网易pomelo官网介绍的使用 WebStorm ...

  4. 2、netlink简介

    Netlink 是一种特殊的 socket,它是 Linux 所特有的,类似于 BSD 中的AF_ROUTE 但又远比它的功能强大,目前在最新的 Linux 内核(2.6.14)中使用netlink ...

  5. Java基础知识强化之网络编程笔记18:Android网络通信之 使用HttpClient的Post / Get 方式读取网络数据(基于HTTP通信技术)

    使用HttpClient进行Get方式通信,通过HttpClient建立网络链接,使用HttpGet方法读取数据,并且通过Response获取Entity返回值. 使用HttpClient进行Post ...

  6. 多线程GCD

    经常使用:规避很多线程相关的复杂的逻辑 为什么会gcd?因为pthread和nsthread要求开发人员对线程相关的知识了解深入; 手动启动线程:加锁/解锁;造成很多隐患 --> 苹果公司给出了 ...

  7. Oracle inactive session (last_call_et)

    注意last_call_et的值, select s.status,s.last_call_et,s.* from v$session s where username='DDD'; 在本例中,开了个 ...

  8. MySQL提供的错误日志中的错误级别一共有3个分别为:

    ERROR_LEVEL-->错误级别 WARNING_LEVEL-->警告级别 INFORMATION_LEVEL-->信息级别

  9. [转]Oracle学习笔记——权限管理

    本文转自:http://www.cnblogs.com/whgw/archive/2011/10/30.html 一.系统的默认用户 1)sys用户是超级用户,具有最高权限,具有sysdba角色,有c ...

  10. [引]LINQ to XML 类概述

    本文转自:http://msdn.microsoft.com/zh-cn/library/bb387023.aspx 本主题提供 System.Xml.Linq 命名空间中 LINQ to XML 类 ...