using Hamp.App.BLL;
using Hamp.App.Model;
using Hamp.App.Model.QualityManagement;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text.RegularExpressions;
using System.Web;
using Excel = Microsoft.Office.Interop.Excel; namespace QualityManagement
{
/// <summary>
/// BaseToExcel 的摘要说明
/// </summary>
public partial class BaseToExcel : System.Web.UI.Page
{
/// <summary>
/// 导出到Excel
/// </summary>
/// <param name="dt"></param>
/// <param name="modQMPA"></param>
/// <param name="strPath"></param>
/// <param name="strExcModel"></param>
public void ToExcel(DataTable dt, QMProblemAnalysisMOD modQMPA, string strCustomerName,string strProjectName)
{
Excel.Range excelRange = m_objExcel.get_Range(m_objExcel.Cells[1, 1], m_objExcel.Cells[27, 15]);
//excelRange.NumberFormat = "@";
excelRange.Font.Color = 1;//黑色字体
//excelRange.WrapText = false;//不换行
Excel.Range excelRange2 = m_objExcel.get_Range(m_objExcel.Cells[7, 1], m_objExcel.Cells[27, 15]);
//excelRange2.WrapText = true;//换行
Excel.Range excelRange3 = m_objExcel.get_Range(m_objExcel.Cells[9, 1], m_objExcel.Cells[12, 12]);
//excelRange3.HorizontalAlignment = Excel.XlHAlign.xlHAlignLeft;
//excelRange3.VerticalAlignment = Excel.XlVAlign.xlVAlignTop;
UserBLL u = new UserBLL();
m_objExcel.Cells[2, 2] = modQMPA.EightDisciplinesNO;
m_objExcel.Cells[5, 3] = strCustomerName;//客户名称
m_objExcel.Cells[5, 5] = strProjectName;//产品编号
m_objExcel.Cells[5, 9] = dt.Rows[0]["DefectQuantity"].ToString();//不良总数
if (dt.Rows[0]["ComplaintsDate"] != DBNull.Value && dt.Rows[0]["ComplaintsDate"] != null)
{//投诉日期
DateTime dtime = new DateTime(1, 1, 1);
if (DateTime.TryParse(dt.Rows[0]["ComplaintsDate"].ToString(), out dtime))
{
m_objExcel.Cells[5, 13] = dtime.ToString("yyyy-MM-dd");
}
}
if (dt.Rows[0]["AddBy"] != DBNull.Value && dt.Rows[0]["AddBy"] != null)
{//问题确认人
UserInfo problemAddBy = u.GetModelByAID(StringUtils.ToInt(dt.Rows[0]["AddBy"]), false);
m_objExcel.Cells[9, 13] = problemAddBy.LastName;
} if (dt.Rows[0]["ShipDate"] != DBNull.Value && dt.Rows[0]["ShipDate"] != null)
{//交货日期
DateTime dtime = new DateTime(1, 1, 1);
if (DateTime.TryParse(dt.Rows[0]["ShipDate"].ToString(), out dtime))
{
m_objExcel.Cells[5, 11] = dtime.ToString("yyyy-MM-dd");
}
}
if (dt.Rows[0]["DeliveryAmount"] != DBNull.Value && dt.Rows[0]["DeliveryAmount"] != null)
{//交货总数
m_objExcel.Cells[5, 7] = dt.Rows[0]["DeliveryAmount"].ToString();
}
m_objExcel.Cells[7, 1] = modQMPA.QualityTeam;
m_objExcel.Cells[9, 1] = StripHTML(modQMPA.Content);
m_objExcel.Cells[15, 1] = modQMPA.QATempSolution;
if (!string.IsNullOrWhiteSpace(modQMPA.QATempExecutor))
{
string tempResponsibleby = "";
string[] TempExecutorArr = modQMPA.QATempExecutor.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
foreach (string item in TempExecutorArr)
{
string[] itemArr = item.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
if (itemArr.Length > 1)
{
tempResponsibleby += itemArr.GetValue(1) + ",";
}
}
m_objExcel.Cells[15, 11] = tempResponsibleby.TrimEnd(',');
}
if (modQMPA.QATempSolveDate.HasValue)
{
m_objExcel.Cells[15, 13] = modQMPA.QATempSolveDate.Value.ToString("yyyy-MM-dd");
}
m_objExcel.Cells[17, 3] = modQMPA.QMOnline;
m_objExcel.Cells[17, 8] = modQMPA.QMInStock;
if (modQMPA.QMOtherCheckBy.HasValue)
{
UserInfo QMOtherCheckBy = u.GetModelByAID(StringUtils.ToInt(modQMPA.QMOtherCheckBy.Value), false) ?? new UserInfo();
m_objExcel.Cells[17, 13] = QMOtherCheckBy.LastName;
}
m_objExcel.Cells[19, 1] = modQMPA.QAAnalysis;
m_objExcel.Cells[19, 13] = modQMPA.AnalysisBy;
m_objExcel.Cells[21, 1] = modQMPA.QAFinalSolution;
if (!string.IsNullOrWhiteSpace(modQMPA.QAFinalExecutor))
{
string FinalResponsibleby = "";
string[] FinalExecutorArr = modQMPA.QAFinalExecutor.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
foreach (string item in FinalExecutorArr)
{
string[] itemArr = item.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
if (itemArr.Length > 1)
{
FinalResponsibleby += itemArr.GetValue(1) + ",";
}
}
m_objExcel.Cells[21, 11] = FinalResponsibleby.TrimEnd(',');
}
m_objExcel.Cells[21, 13] = modQMPA.QAFinalSolveDate;
m_objExcel.Cells[23, 1] = modQMPA.ResultConfirm;
if (modQMPA.ResultCheckedBy.HasValue)
{
UserInfo ResultCheckedBy = u.GetModelByAID(StringUtils.ToInt(modQMPA.ResultCheckedBy.Value), false) ?? new UserInfo();
m_objExcel.Cells[23, 11] = ResultCheckedBy.LastName;
}
m_objExcel.Cells[23, 13] = modQMPA.ResultCheckedDate;
m_objExcel.Cells[25, 1] = modQMPA.PreventAction;
if (modQMPA.Approver.HasValue)
{
UserInfo ApproverUser = u.GetModelByAID(StringUtils.ToInt(modQMPA.Approver.Value), false) ?? new UserInfo();
m_objExcel.Cells[25, 11] = ApproverUser.LastName;
}
m_objExcel.Cells[25, 13] = modQMPA.VerifyDate;
if (modQMPA.IsFinished.HasValue)
{
if (modQMPA.IsFinished.Value)
{
m_objExcel.Cells[27, 4] = "YES /是";
}
else
{
m_objExcel.Cells[27, 4] = "No /非";
}
}
} /// <summary>
/// 功能:实现Excel应用程序的打开
/// </summary>
/// <param name="TemplateFilePath">模板文件物理路径</param>
public void Open(string TemplateFilePath)
{
//打开对象
m_objExcel = new Excel.Application();
m_objExcel.Visible = false;
m_objExcel.DisplayAlerts = false; if (m_objExcel.Version != "11.0")
{
// MessageBox.Show("您的 Excel 版本不是 11.0 (Office 2003),操作可能会出现问题。");
//m_objExcel.Quit();
//return;
} m_objBooks = (Excel.Workbooks)m_objExcel.Workbooks;
if (TemplateFilePath.Equals(String.Empty))
{
m_objBook = (Excel._Workbook)(m_objBooks.Add(m_objOpt));
}
else
{
m_objBook = m_objBooks.Open(TemplateFilePath, m_objOpt, m_objOpt, m_objOpt, m_objOpt,
m_objOpt, m_objOpt, m_objOpt, m_objOpt, m_objOpt, m_objOpt, m_objOpt, m_objOpt, m_objOpt, m_objOpt);
}
m_objSheets = (Excel.Sheets)m_objBook.Worksheets;
m_objSheet = (Excel._Worksheet)(m_objSheets.get_Item(1));
m_objExcel.WorkbookBeforeClose += new Excel.AppEvents_WorkbookBeforeCloseEventHandler(m_objExcel_WorkbookBeforeClose);
} private void m_objExcel_WorkbookBeforeClose(Excel.Workbook m_objBooks, ref bool _Cancel)
{
// MessageBox.Show("保存完毕!");
} /// <summary>
/// 将图片插入到指定的单元格位置。
/// 注意:图片必须是绝对物理路径
/// </summary>
/// <param name="RangeName">单元格名称,例如:B4</param>
/// <param name="PicturePath">要插入图片的绝对路径。</param>
public void InsertPicture(string RangeName, string PicturePath)
{
m_objRange = m_objSheet.get_Range(RangeName, m_objOpt);
m_objRange.Select();
Excel.Pictures pics = (Excel.Pictures)m_objSheet.Pictures(m_objOpt);
pics.Insert(PicturePath, m_objOpt);
} /// <summary>
/// 将图片插入到指定的单元格位置,并设置图片的宽度和高度。
/// 注意:图片必须是绝对物理路径
/// </summary>
/// <param name="RangeName">单元格名称,例如:B4</param>
/// <param name="PicturePath">要插入图片的绝对路径。</param>
/// <param name="PictuteWidth">插入后,图片在Excel中显示的宽度。</param>
/// <param name="PictureHeight">插入后,图片在Excel中显示的高度。</param>
public void InsertPicture(string RangeName, string PicturePath, float PictuteWidth, float PictureHeight)
{
m_objRange = m_objSheet.get_Range(RangeName, m_objOpt);
m_objRange.Select();
float PicLeft, PicTop;
PicLeft = Convert.ToSingle(m_objRange.Left);
PicTop = Convert.ToSingle(m_objRange.Top);
//参数含义:
//图片路径
//是否链接到文件
//图片插入时是否随文档一起保存
//图片在文档中的坐标位置(单位:points)
//图片显示的宽度和高度(单位:points)
m_objSheet.Shapes.AddPicture(PicturePath, Microsoft.Office.Core.MsoTriState.msoFalse,
Microsoft.Office.Core.MsoTriState.msoTrue, PicLeft, PicTop, PictuteWidth, PictureHeight);
} /// <summary>
/// 将Excel文件保存到指定的目录,目录必须事先存在,文件名称不一定要存在。
/// </summary>
/// <param name="OutputFilePath">要保存成的文件的全路径。</param>
public void SaveFile(string OutputFilePath)
{
if (System.IO.File.Exists(OutputFilePath))
{
System.IO.File.Delete(OutputFilePath);
} m_objBook.SaveAs(OutputFilePath, m_objOpt, m_objOpt,
m_objOpt, m_objOpt, m_objOpt, Excel.XlSaveAsAccessMode.xlNoChange,
m_objOpt, m_objOpt, m_objOpt, m_objOpt, m_objOpt); this.Close();
}
/// <summary>
/// 关闭应用程序
/// </summary>
private void Close()
{
m_objBook.Close(false, m_objOpt, m_objOpt);
m_objExcel.Quit();
} /// <summary>
/// 释放所引用的COM对象。注意:这个过程一定要执行。
/// </summary>
public void Dispose()
{
ReleaseObj(m_objSheets);
ReleaseObj(m_objBook);
ReleaseObj(m_objBooks);
ReleaseObj(m_objExcel);
System.GC.Collect();
System.GC.WaitForPendingFinalizers();
}
/// <summary>
/// 释放对象,内部调用
/// </summary>
/// <param name="o"></param>
private void ReleaseObj(object o)
{
try
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(o);
}
catch { }
finally { o = null; }
}
/// <summary>
/// 從WEB頁面文件下載
/// </summary>
/// <param name="strFile">要下載的文件的絕對路徑 </param>
public void DownloadFile(string strFile)
{
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.ContentType = "application/octet-stream";
HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=\"" + HttpUtility.UrlEncode(System.IO.Path.GetFileName(strFile).Trim()) + "\"");
HttpContext.Current.Response.Flush(); HttpContext.Current.Response.WriteFile(strFile);
HttpContext.Current.Response.End();
} private Excel.Application m_objExcel = null;
private Excel.Workbooks m_objBooks = null;
private Excel._Workbook m_objBook = null;
private Excel.Sheets m_objSheets = null;
private Excel._Worksheet m_objSheet = null;
private Excel.Range m_objRange = null;
private object m_objOpt = System.Reflection.Missing.Value; /// <summary>
/// 去除HTML标记
/// </summary>
/// <param name="strHtml">包括HTML的源码 </param>
/// <returns>已经去除后的文字</returns>
public string StripHTML(string strHtml)
{
string[] aryReg =
{
@"<script[^>]*?>.*?</script>",
@"<(\/\s*)?!?((\w+:)?\w+)(\w+(\s*=?\s*(([""'])(\\[""'tbnr]|[^\7])*?\7|\w+)|.{0})|\s)*?(\/\s*)?>", @"([\r\n])[\s]+", @"&(quot|#34);",
@"&(amp|#38);", @"&(lt|#60);", @"&(gt|#62);", @"&(nbsp|#160);", @"&(iexcl|#161);", @"&(cent|#162);",
@"&(pound|#163);",@"&(copy|#169);", @"&#(\d+);", @"-->", @"<!--.*\n"
}; string[] aryRep =
{
"", "", "", "\"", "&", "<", ">", " ", "\xa1", //chr(161),
"\xa2", //chr(162),
"\xa3", //chr(163),
"\xa9", //chr(169),
"", "\r\n", ""
}; string newReg = aryReg[0];
string strOutput = strHtml;
for (int i = 0; i < aryReg.Length; i++)
{
Regex regex = new Regex(aryReg[i], RegexOptions.IgnoreCase);
strOutput = regex.Replace(strOutput, aryRep[i]);
}
strOutput.Replace("<", "");
strOutput.Replace(">", "");
strOutput.Replace("\r\n", "");
return strOutput;
}
/// <summary>
/// 取出图片地址
/// </summary>
/// <param name="HTMLStr"></param>
/// <returns></returns>
public string[] GetImgUrl(string HTMLStr)
{
// 定义正则表达式用来匹配 img 标签
Regex regImg = new Regex(@"<img\b[^<>]*?\bsrc[\s\t\r\n]*=[\s\t\r\n]*[""']?[\s\t\r\n]*(?<imgUrl>[^\s\t\r\n""'<>]*)[^<>]*?/?[\s\t\r\n]*>", RegexOptions.IgnoreCase); // 搜索匹配的字符串
MatchCollection matches = regImg.Matches(HTMLStr); int i = 0;
string[] sUrlList = new string[matches.Count]; // 取得匹配项列表
foreach (Match match in matches)
sUrlList[i++] = match.Groups["imgUrl"].Value; return sUrlList;
} }
}

调用方法

string strExcelTemplate = Server.MapPath("~/file/Protected/QualityManagement/AnalysisReport/test.xlsx");
base.Open(strExcelTemplate);
base.ToExcel(dt, modQMPA, strCustomerName, strProjectName);
string[] imgSrc = base.GetImgUrl(modQMPA.Content);
foreach (string itemsrc in imgSrc)
{
string PicturePath = itemsrc;
string uri = Request.Url.AbsoluteUri.ToLower() ?? "";
string strUri = uri.Substring(0, uri.IndexOf("webfile"));
if (PicturePath.Contains(strUri + "WebFile/"))
{
PicturePath = PicturePath.Replace(strUri + "WebFile/", "/WebFile/");
}
PicturePath = Server.MapPath(PicturePath); base.InsertPicture("A11", PicturePath, 330, 210);
}
string strPath = "~/file/public/QualityManagement/test.xlsx";
string filePath = Server.MapPath(strPath);
base.SaveFile(filePath); if (System.IO.File.Exists(filePath))
{
base.DownloadFile(strPath);
}
Dispose();

C# 常用的Excel 格式化操作 及 常用颜色定义对应Excel中颜色名

http://blog.163.com/jackie_dai@126/blog/static/34830764201171142848285/

 

.net导出不规则Excel的更多相关文章

  1. DataTable导出到Excel

    简单的导出到Excel中: 代码如下: using System; using System.Collections.Generic; using System.Data; using System. ...

  2. ASP.NET中GridView数据导出到Excel

    /// <summary> /// 导出按钮 /// </summary> /// <param name="sender"></para ...

  3. 【Java EE 学习 17 下】【数据库导出到Excel】【多条件查询方法】

    一.导出到Excel 1.使用DatabaseMetaData分析数据库的数据结构和相关信息. (1)测试得到所有数据库名: private static DataSource ds=DataSour ...

  4. PB的datawindow导出到excel文件(使用saveasascii)

    **********************************************************//*函数名称:uf_dwsaveas_excel功能:将数据窗口数据导出EXCEL ...

  5. 纯JS 将table表格导出到excel

    html <div > <button type="button" onclick="getXlsFromTbl('tableExcel','myDiv ...

  6. 将页面上的内容导出到Excel

    <asp:Button ID="lkbExport" runat="server" Name="Save" Text="导出 ...

  7. asp.net教程:GridView导出到Excel或Word文件

    asp.net教程:GridView导出到Excel或Word文件</ br> 在项目中我们经常会遇到要求将一些数据导出成Excel或者Word表格的情况,比如中国移动(我是中国移动用户) ...

  8. DataGridView导出到Excel的三个方法

    #region DataGridView数据显示到Excel /// <summary> /// 打开Excel并将DataGridView控件中数据导出到Excel /// </s ...

  9. salesforce 零基础学习(二十三)数据记录导出至excel(自定义报表导出)

    我们都知道,报表有个功能为导出excel,但是有的时候客户需求往往标准的报表达不到,比如导出excel,其中本月修改的数据字段标红,如下图所示. 这就需要我们去写VF来实现此功能. 需求:将数据表记录 ...

随机推荐

  1. 大数据应用日志采集之Scribe演示实例完全解析

    大数据应用日志采集之Scribe演示实例完全解析 引子: Scribe是Facebook开源的日志收集系统,在Facebook内部已经得到大量的应用.它能够从各种日志源上收集日志,存储到一个中央存储系 ...

  2. 了解OData(一)

    了解OData(一) 最近做了一个小项目,其中用到了 WCF Data Service,之前是叫 ADO.NET Data Service 的.关于WCF Data Service,博客园里的介绍并不 ...

  3. DEV gridcontrol 设置行数据超宽换行

    第一 在main > columns 的 某个gridcolumn下的 columnEdit为新建为 repositoryitemmemoedit 第二 repositor下的optionvie ...

  4. centos 6.4 x64安装bugfree

    第一步:下载xampp-linux-1.8.1.tar.gz [root@SVNMANAGER ~]# tar -zxvf xampp-linux-1.8.1.tar.gz -C /opt [root ...

  5. 横瓜执导众程序员开展大讨论关于C、JAVA及其它主流IT技术使用情况和优点缺点。

    横瓜执导众程序员开展大讨论关于C.JAVA及其它主流IT技术使用情况和优点缺点. 遥执乾坤(44758121)  18:21:23 mysql据说只能使用一个索引,我这里几乎所有字段都有索引. 但每个 ...

  6. mysql提示Column count doesn't match value count at row 1错误

    mysql提示Column count doesn't match value count at row 1错误,后来发现是由于写的SQL语句里列的数目和后面的值的数目不一致, 比如insert in ...

  7. 简单的通讯录(C语言实现)

    通讯录实现的功能 --: .添加联系人 .删除联系人 .查找联系人 .修改联系人 .显示联系人 .清空通讯录 .按照姓名进行排序 .退出程序 该通讯录将联系人的信息保存在文件中 在VS2013中打开文 ...

  8. OC之知识储备篇

    1. Objective-C是基于C语言的. a. 在C语言的基础之上新增了面向对象的语法. b. 将C语言中复杂的.繁琐的语法封装的更为简单. 2. Objective-C程序的源文件的后缀名.m  ...

  9. pch文件的作用和配置

    pch文件说白了就是一个头文件,只不过这个头文件的类在全局都可以使用,所以说非常的方便,并不用在每个类里面都写一些重复类的头文件,只要将用到的类的头文件放到pch文件里面就行了,当然了还有就是宏定义, ...

  10. 如何成为一名hacker?

    很多人问我如何成为黑客,一般来说我总是会扯一大堆废话,告诉他们要时刻保持好奇心,要学会打破规则挑战权威之类的. 但这类话肯定不是提问者想听的.我揣摩了一下他们的心情,他们想问的应该是这个问题:如何学习 ...