3、C# 文件处理工具集
1、上传
2、文件下载
using System; using System.Data; using System.Text; using System.Configuration; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.HtmlControls; using System.Web.UI.WebControls; using System.Collections; using System.Text.RegularExpressions; using System.IO; using System.Data.OleDb; using System.Data.OracleClient; using System.Data.SqlClient; public static void download(string fn) { fn = HttpContext.Current.Request.MapPath(fn); FileInfo DownloadFile; try { DownloadFile = new FileInfo(fn); //设置要下载的文件 if (!System.IO.File.Exists(fn)) { System.Web.HttpContext.Current.Response.Clear(); System.Web.HttpContext.Current.Response.Write("对不起,无法下载,因为文件不存在!<br/>"); System.Web.HttpContext.Current.Response.End(); } //MJ.ExecuteSQL("insert into lcdfw_downlog(downlog_fileid,downlog_username,downlog_ip) values('" + id + "','" + Session["ktcoausername"] + "','" + Request.UserHostAddress.ToString() + "')"); System.Web.HttpContext.Current.Response.Clear(); //清除缓冲区流中的所有内容输出 System.Web.HttpContext.Current.Response.ClearHeaders(); //清除缓冲区流中的所有头,不知道为什么,不写这句会显示错误页面 System.Web.HttpContext.Current.Response.Buffer = false; //设置缓冲输出为false //设置输出流的 HTTP MIME 类型 //取文件扩展名 switch (DownloadFile.Extension) { case ".zip": System.Web.HttpContext.Current.Response.ContentType = "application/zip"; break; case ".xls": System.Web.HttpContext.Current.Response.ContentType = "application/vnd.ms-excel"; break; case ".bin": System.Web.HttpContext.Current.Response.ContentType = "application/octet-stream"; break; case ".hex": System.Web.HttpContext.Current.Response.ContentType = "application/octet-stream"; break; case ".pdf": System.Web.HttpContext.Current.Response.ContentType = "application/pdf"; break; case ".rar": System.Web.HttpContext.Current.Response.ContentType = "application/rar"; break; case ".doc": System.Web.HttpContext.Current.Response.ContentType = "application/msword"; break; default: System.Web.HttpContext.Current.Response.ContentType = "application/unknow"; break; } //新命名文件名 string NewFileName = fn; //NewFileName += MJ.GetDataSet("select data_panel+'_'+data_mb+'_'+'_'+(case left(data_logo,8) when 'imgLogo_' then '图片LOGO' else data_logo end) from lcdfw_data where id=" + Request["id"]).Tables[0].Rows[0][0].ToString(); System.Text.RegularExpressions.Regex re = new Regex(@"[\\,\/,\:,\*,\?]", RegexOptions.IgnoreCase);//正则替换地址为红色用 NewFileName = re.Replace(NewFileName, ""); //将 HTTP 头添加到输出流 System.Web.HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.Default; //Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(NewFileName+index + DownloadFile.Extension, System.Text.Encoding.UTF8)); System.Web.HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(fn, System.Text.Encoding.UTF8)); System.Web.HttpContext.Current.Response.AppendHeader("Content-Length", DownloadFile.Length.ToString()); System.Web.HttpContext.Current.Response.Charset = "UTF-8"; //将指定的文件直接写入 HTTP 内容输出流。 //一定要注意是WriteFile不是Write System.Web.HttpContext.Current.Response.WriteFile(DownloadFile.FullName); System.Web.HttpContext.Current.Response.Flush(); //向客户端发送当前所有缓冲的输出 System.Web.HttpContext.Current.Response.End(); //将当前所有缓冲的输出发送到客户端,这句户有时候会出错,可以尝试把这句话放在整个函数的最后一行。 //也可以用HttpContext.Current.ApplicationInstance.CompleteRequest ()方法代替 } catch (Exception err) { System.Web.HttpContext.Current.Response.Write("无法下载文件:" + fn + ",由于:" + err.Message); System.Web.HttpContext.Current.Response.End(); } }
3、导出
(1)导出Excel
using System.Data; using System.Configuration; using System.Web; using System.IO; using System.Text; using NPOI; using NPOI.HPSF; using NPOI.HSSF; using NPOI.HSSF.UserModel; using NPOI.HSSF.Util; using NPOI.POIFS; using NPOI.Util; using System.Windows.Forms; /// <summary> /// DataTable导出到Excel文件 /// </summary> /// <param name="dtSource">源DataTable</param> /// <param name="strHeaderText">表头文本</param> /// <param name="strFileName">保存位置</param> public static void DataTableToExcel(DataTable dtSource, string strHeaderText, string strFileName) { using (MemoryStream ms = DataTableToExcel(dtSource, strHeaderText)) { using (FileStream fs = new FileStream(strFileName, FileMode.Create, FileAccess.Write)) { byte[] data = ms.ToArray(); fs.Write(data, 0, data.Length); fs.Flush(); } } } /// <summary> /// DataGridView导出到Excel文件 /// </summary> /// <param name="dtSource">源DataTGridview</param> /// <param name="strHeaderText">表头文本</param> /// <param name="strFileName">保存位置</param> public static void DataGridViewToExcel(DataGridView myDgv, string strHeaderText, string strFileName) { using (MemoryStream ms = DataGridViewToExcel(myDgv, strHeaderText)) { using (FileStream fs = new FileStream(strFileName, FileMode.Create, FileAccess.Write)) { byte[] data = ms.ToArray(); fs.Write(data, 0, data.Length); fs.Flush(); } } } /// <summary> /// DataTable导出到Excel的MemoryStream /// </summary> /// <param name="dtSource">源DataTable</param> /// <param name="strHeaderText">表头文本</param> public static MemoryStream DataTableToExcel(DataTable dtSource, string strHeaderText) { HSSFWorkbook workbook = new HSSFWorkbook(); HSSFSheet sheet = (HSSFSheet)workbook.CreateSheet(); #region 右击文件 属性信息 { DocumentSummaryInformation dsi = PropertySetFactory.CreateDocumentSummaryInformation(); dsi.Company = "NPOI"; workbook.DocumentSummaryInformation = dsi; SummaryInformation si = PropertySetFactory.CreateSummaryInformation(); si.Author = "文件作者信息"; //填加xls文件作者信息 si.ApplicationName = "创建程序信息"; //填加xls文件创建程序信息 si.LastAuthor = "最后保存者信息"; //填加xls文件最后保存者信息 si.Comments = "作者信息"; //填加xls文件作者信息 si.Title = "标题信息"; //填加xls文件标题信息 si.Subject = "主题信息";//填加文件主题信息 si.CreateDateTime = System.DateTime.Now; workbook.SummaryInformation = si; } #endregion HSSFCellStyle dateStyle = (HSSFCellStyle)workbook.CreateCellStyle(); HSSFDataFormat format = (HSSFDataFormat)workbook.CreateDataFormat(); dateStyle.DataFormat = format.GetFormat("yyyy-mm-dd"); //取得列宽 int[] arrColWidth = new int[dtSource.Columns.Count]; foreach (DataColumn item in dtSource.Columns) { arrColWidth[item.Ordinal] = Encoding.GetEncoding(936).GetBytes(item.ColumnName.ToString()).Length; } for (int i = 0; i < dtSource.Rows.Count; i++) { for (int j = 0; j < dtSource.Columns.Count; j++) { int intTemp = Encoding.GetEncoding(936).GetBytes(dtSource.Rows[i][j].ToString()).Length; if (intTemp > arrColWidth[j]) { arrColWidth[j] = intTemp; } } } int rowIndex = 0; foreach (DataRow row in dtSource.Rows) { #region 新建表,填充表头,填充列头,样式 if (rowIndex == 65535 || rowIndex == 0) { if (rowIndex != 0) { sheet = (HSSFSheet)workbook.CreateSheet(); } #region 表头及样式 { HSSFRow headerRow = (HSSFRow)sheet.CreateRow(0); headerRow.HeightInPoints = 25; headerRow.CreateCell(0).SetCellValue(strHeaderText); HSSFCellStyle headStyle = (HSSFCellStyle)workbook.CreateCellStyle(); // headStyle.Alignment = CellHorizontalAlignment.CENTER; HSSFFont font = (HSSFFont)workbook.CreateFont(); font.FontHeightInPoints = 20; font.Boldweight = 700; headStyle.SetFont(font); headerRow.GetCell(0).CellStyle = headStyle; // sheet.AddMergedRegion(new Region(0, 0, 0, dtSource.Columns.Count - 1)); //headerRow.Dispose(); } #endregion #region 列头及样式 { HSSFRow headerRow = (HSSFRow)sheet.CreateRow(1); HSSFCellStyle headStyle = (HSSFCellStyle)workbook.CreateCellStyle(); //headStyle.Alignment = CellHorizontalAlignment.CENTER; HSSFFont font = (HSSFFont)workbook.CreateFont(); font.FontHeightInPoints = 10; font.Boldweight = 700; headStyle.SetFont(font); foreach (DataColumn column in dtSource.Columns) { headerRow.CreateCell(column.Ordinal).SetCellValue(column.ColumnName); headerRow.GetCell(column.Ordinal).CellStyle = headStyle; //设置列宽 sheet.SetColumnWidth(column.Ordinal, (arrColWidth[column.Ordinal] + 1) * 256); } // headerRow.Dispose(); } #endregion rowIndex = 2; } #endregion #region 填充内容 HSSFRow dataRow = (HSSFRow)sheet.CreateRow(rowIndex); foreach (DataColumn column in dtSource.Columns) { HSSFCell newCell = (HSSFCell)dataRow.CreateCell(column.Ordinal); string drValue = row[column].ToString(); switch (column.DataType.ToString()) { case "System.String"://字符串类型 newCell.SetCellValue(drValue); break; case "System.DateTime"://日期类型 System.DateTime dateV; System.DateTime.TryParse(drValue, out dateV); newCell.SetCellValue(dateV); newCell.CellStyle = dateStyle;//格式化显示 break; case "System.Boolean"://布尔型 bool boolV = false; bool.TryParse(drValue, out boolV); newCell.SetCellValue(boolV); break; case "System.Int16"://整型 case "System.Int32": case "System.Int64": case "System.Byte": int intV = 0; int.TryParse(drValue, out intV); newCell.SetCellValue(intV); break; case "System.Decimal"://浮点型 case "System.Double": double doubV = 0; double.TryParse(drValue, out doubV); newCell.SetCellValue(doubV); break; case "System.DBNull"://空值处理 newCell.SetCellValue(""); break; default: newCell.SetCellValue(""); break; } } #endregion rowIndex++; } using (MemoryStream ms = new MemoryStream()) { workbook.Write(ms); ms.Flush(); ms.Position = 0; sheet.Dispose(); //workbook.Dispose();//一般只用写这一个就OK了,他会遍历并释放所有资源,但当前版本有问题所以只释放sheet return ms; } } /// <summary> /// DataTable导出到Excel的MemoryStream /// </summary> /// <param name="myDgv">源DataTable</param> /// <param name="strHeaderText">表头文本</param> public static MemoryStream DataGridViewToExcel(DataGridView myDgv, string strHeaderText) { HSSFWorkbook workbook = new HSSFWorkbook(); HSSFSheet sheet = (HSSFSheet)workbook.CreateSheet(); #region 右击文件 属性信息 { DocumentSummaryInformation dsi = PropertySetFactory.CreateDocumentSummaryInformation(); dsi.Company = "NPOI"; workbook.DocumentSummaryInformation = dsi; SummaryInformation si = PropertySetFactory.CreateSummaryInformation(); si.Author = "文件作者信息"; //填加xls文件作者信息 si.ApplicationName = "创建程序信息"; //填加xls文件创建程序信息 si.LastAuthor = "最后保存者信息"; //填加xls文件最后保存者信息 si.Comments = "作者信息"; //填加xls文件作者信息 si.Title = "标题信息"; //填加xls文件标题信息 si.Subject = "主题信息";//填加文件主题信息 si.CreateDateTime = System.DateTime.Now; workbook.SummaryInformation = si; } #endregion HSSFCellStyle dateStyle = (HSSFCellStyle)workbook.CreateCellStyle(); HSSFDataFormat format = (HSSFDataFormat)workbook.CreateDataFormat(); dateStyle.DataFormat = format.GetFormat("yyyy-mm-dd"); //取得列宽 int[] arrColWidth = new int[myDgv.Columns.Count]; foreach (DataGridViewColumn item in myDgv.Columns) { arrColWidth[item.Index] = Encoding.GetEncoding(936).GetBytes(item.HeaderText.ToString()).Length; } for (int i = 0; i < myDgv.Rows.Count; i++) { for (int j = 0; j < myDgv.Columns.Count; j++) { int intTemp = Encoding.GetEncoding(936).GetBytes(myDgv.Rows[i].Cells[j].ToString()).Length; if (intTemp > arrColWidth[j]) { arrColWidth[j] = intTemp; } } } int rowIndex = 0; foreach (DataGridViewRow row in myDgv.Rows) { #region 新建表,填充表头,填充列头,样式 if (rowIndex == 65535 || rowIndex == 0) { if (rowIndex != 0) { sheet = (HSSFSheet)workbook.CreateSheet(); } #region 表头及样式 { HSSFRow headerRow = (HSSFRow)sheet.CreateRow(0); headerRow.HeightInPoints = 25; headerRow.CreateCell(0).SetCellValue(strHeaderText); HSSFCellStyle headStyle = (HSSFCellStyle)workbook.CreateCellStyle(); // headStyle.Alignment = CellHorizontalAlignment.CENTER; HSSFFont font = (HSSFFont)workbook.CreateFont(); font.FontHeightInPoints = 20; font.Boldweight = 700; headStyle.SetFont(font); headerRow.GetCell(0).CellStyle = headStyle; // sheet.AddMergedRegion(new Region(0, 0, 0, dtSource.Columns.Count - 1)); //headerRow.Dispose(); } #endregion #region 列头及样式 { HSSFRow headerRow = (HSSFRow)sheet.CreateRow(1); HSSFCellStyle headStyle = (HSSFCellStyle)workbook.CreateCellStyle(); //headStyle.Alignment = CellHorizontalAlignment.CENTER; HSSFFont font = (HSSFFont)workbook.CreateFont(); font.FontHeightInPoints = 10; font.Boldweight = 700; headStyle.SetFont(font); foreach (DataGridViewColumn column in myDgv.Columns) { headerRow.CreateCell(column.Index).SetCellValue(column.HeaderText); headerRow.GetCell(column.Index).CellStyle = headStyle; //设置列宽 sheet.SetColumnWidth(column.Index, (arrColWidth[column.Index] + 1) * 256); } // headerRow.Dispose(); } #endregion rowIndex = 2; } #endregion #region 填充内容 HSSFRow dataRow = (HSSFRow)sheet.CreateRow(rowIndex); if (row.Index > 0) { foreach (DataGridViewColumn column in myDgv.Columns) { HSSFCell newCell = (HSSFCell)dataRow.CreateCell(column.Index); string drValue = myDgv[column.Index, row.Index - 1].Value.ToString(); switch (column.ValueType.ToString()) { case "System.String"://字符串类型 newCell.SetCellValue(drValue); break; case "System.DateTime"://日期类型 System.DateTime dateV; System.DateTime.TryParse(drValue, out dateV); newCell.SetCellValue(dateV); newCell.CellStyle = dateStyle;//格式化显示 break; case "System.Boolean"://布尔型 bool boolV = false; bool.TryParse(drValue, out boolV); newCell.SetCellValue(boolV); break; case "System.Int16"://整型 case "System.Int32": case "System.Int64": case "System.Byte": int intV = 0; int.TryParse(drValue, out intV); newCell.SetCellValue(intV); break; case "System.Decimal"://浮点型 case "System.Double": double doubV = 0; double.TryParse(drValue, out doubV); newCell.SetCellValue(doubV); break; case "System.DBNull"://空值处理 newCell.SetCellValue(""); break; default: newCell.SetCellValue(""); break; } } } else { rowIndex--; } #endregion rowIndex++; } using (MemoryStream ms = new MemoryStream()) { workbook.Write(ms); ms.Flush(); ms.Position = 0; sheet.Dispose(); //workbook.Dispose();//一般只用写这一个就OK了,他会遍历并释放所有资源,但当前版本有问题所以只释放sheet return ms; } }
(2)导出PDF
using System; using System.IO; using System.Text; using System.Collections; using System.Data; public class PDFGenerator { public PDFGenerator() { } static float pageWidth = 594.0f; static float pageDepth = 828.0f; static float pageMargin = 30.0f; static float fontSize = 20.0f; static float leadSize = 10.0f; static StreamWriter pPDF = new StreamWriter("D:\\wwwroot\\mjerp\\myPDF.pdf"); static MemoryStream mPDF = new MemoryStream(); private void ConvertToByteAndAddtoStream(string strMsg) { Byte[] buffer = null; buffer = ASCIIEncoding.ASCII.GetBytes(strMsg); mPDF.Write(buffer, 0, buffer.Length); buffer = null; } private string xRefFormatting(long xValue) { string strMsg = xValue.ToString(); int iLen = strMsg.Length; if (iLen < 10) { StringBuilder s = new StringBuilder(); int i = 10 - iLen; s.Append('0', i); strMsg = s.ToString() + strMsg; } return strMsg; } public void ExportPdf(DataTable dt) { ArrayList xRefs = new ArrayList(); //Byte[] buffer=null; float yPos = 0f; long streamStart = 0; long streamEnd = 0; long streamLen = 0; string strPDFMessage = null; //PDF文档头信息 strPDFMessage = "%PDF-1.1\n"; ConvertToByteAndAddtoStream(strPDFMessage); xRefs.Add(mPDF.Length); strPDFMessage = "1 0 obj\n"; ConvertToByteAndAddtoStream(strPDFMessage); strPDFMessage = " < < /Length 2 0 R >>\n"; ConvertToByteAndAddtoStream(strPDFMessage); strPDFMessage = "stream\n"; ConvertToByteAndAddtoStream(strPDFMessage); ////////PDF文档描述 streamStart = mPDF.Length; //字体 strPDFMessage = "BT\n/F0 " + fontSize + " Tf\n"; ConvertToByteAndAddtoStream(strPDFMessage); //PDF文档实体高度 yPos = pageDepth - pageMargin; strPDFMessage = pageMargin + " " + yPos + " Td\n"; ConvertToByteAndAddtoStream(strPDFMessage); strPDFMessage = leadSize + " TL\n"; ConvertToByteAndAddtoStream(strPDFMessage); //实体内容 for (int i = 0; i < dt.Rows.Count; i++) { for (int j = 0; j < dt.Columns.Count; j++) { strPDFMessage = "(" + dt.Rows[i][j].ToString() + ")Tj\n" + "\n"; ConvertToByteAndAddtoStream(strPDFMessage); } } strPDFMessage = "ET\n"; ConvertToByteAndAddtoStream(strPDFMessage); streamEnd = mPDF.Length; streamLen = streamEnd - streamStart; strPDFMessage = "endstream\nendobj\n"; ConvertToByteAndAddtoStream(strPDFMessage); //PDF文档的版本信息 xRefs.Add(mPDF.Length); strPDFMessage = "2 0 obj\n" + streamLen + "\nendobj\n"; ConvertToByteAndAddtoStream(strPDFMessage); xRefs.Add(mPDF.Length); strPDFMessage = "3 0 obj\n < </Type/Page/Parent 4 0 R/Contents 1 0 R>>\nendobj\n"; ConvertToByteAndAddtoStream(strPDFMessage); xRefs.Add(mPDF.Length); strPDFMessage = "4 0 obj\n < </Type /Pages /Count 1\n"; ConvertToByteAndAddtoStream(strPDFMessage); strPDFMessage = "/Kids[\n3 0 R\n]\n"; ConvertToByteAndAddtoStream(strPDFMessage); strPDFMessage = "/Resources < </ProcSet[/PDF/Text]/Font < </F0 5 0 R>> >>\n"; ConvertToByteAndAddtoStream(strPDFMessage); strPDFMessage = "/MediaBox [ 0 0 " + pageWidth + " " + pageDepth + " ]\n>>\nendobj\n"; ConvertToByteAndAddtoStream(strPDFMessage); xRefs.Add(mPDF.Length); strPDFMessage = "5 0 obj\n < </Type/Font/Subtype/Type1/BaseFont/Courier/Encoding/WinAnsiEncoding>>\nendobj\n"; ConvertToByteAndAddtoStream(strPDFMessage); xRefs.Add(mPDF.Length); strPDFMessage = "6 0 obj\n < </Type/Catalog/Pages 4 0 R>>\nendobj\n"; ConvertToByteAndAddtoStream(strPDFMessage); streamStart = mPDF.Length; strPDFMessage = "xref\n0 7\n0000000000 65535 f \n"; for (int i = 0; i < xRefs.Count; i++) { strPDFMessage += xRefFormatting((long)xRefs[i]) + " 00000 n \n"; } ConvertToByteAndAddtoStream(strPDFMessage); strPDFMessage = "trailer\n < <\n/Size " + (xRefs.Count + 1) + "\n/Root 6 0 R\n>>\n"; ConvertToByteAndAddtoStream(strPDFMessage); strPDFMessage = "startxref\n" + streamStart + "\n%%EOF\n"; ConvertToByteAndAddtoStream(strPDFMessage); mPDF.WriteTo(pPDF.BaseStream); //System.Web.HttpContext.Current.Response.Write(pPDF.BaseStream); mPDF.Close(); pPDF.Close(); } }
4、删除
5、打印
6、查看
7、读取Excel
/// <summary>读取excel /// 默认第一行为标头 /// </summary> /// <param name="strFileName">excel文档路径</param> /// <returns></returns> public static DataTable Import(string strFileName) { DataTable dt = new DataTable(); HSSFWorkbook hssfworkbook; using (FileStream file = new FileStream(strFileName, FileMode.Open, FileAccess.Read)) { hssfworkbook = new HSSFWorkbook(file); } HSSFSheet sheet = (HSSFSheet)hssfworkbook.GetSheetAt(0); System.Collections.IEnumerator rows = sheet.GetRowEnumerator(); HSSFRow headerRow = (HSSFRow)sheet.GetRow(0); int cellCount = headerRow.LastCellNum; for (int j = 0; j < cellCount; j++) { HSSFCell cell = (HSSFCell)headerRow.GetCell(j); dt.Columns.Add(cell.ToString()); } for (int i = (sheet.FirstRowNum + 1); i <= sheet.LastRowNum; i++) { HSSFRow row = (HSSFRow)sheet.GetRow(i); DataRow dataRow = dt.NewRow(); for (int j = row.FirstCellNum; j < cellCount; j++) { if (row.GetCell(j) != null) dataRow[j] = row.GetCell(j).ToString(); } dt.Rows.Add(dataRow); } return dt; }
与你共亲到无可亲密时,便知友谊万岁是尽头。