//https://www.microsoft.com/en-us/download/details.aspx?id=5124  Open XML SDK 2.0 for Microsoft Office
//https://www.microsoft.com/en-us/download/details.aspx?id=30425 Open XML SDK 2.5 for Microsoft Office
//https://github.com/OfficeDev/Open-Xml-Sdk
//http://www.codeproject.com/Tips/366446/Export-GridView-Data-to-Excel-using-OpenXml
//https://openxmlsdkjs.codeplex.com/
//引用: WindowsBase.DLL C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.0\WindowsBase.dll /// <summary>
///
/// </summary>
internal class ExcelHelper
{ /// <summary>
///
/// </summary>
internal class ColumnCaption
{
private static string[] Alphabets = { "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z" };
private static ColumnCaption instance = null;
private List<string> cellHeaders = null;
public static ColumnCaption Instance
{
get
{
if (instance == null)
return new ColumnCaption();
else return ColumnCaption.Instance;
}
}
/// <summary>
///
/// </summary>
public ColumnCaption()
{
this.InitCollection();
}
/// <summary>
///
/// </summary>
private void InitCollection()
{
cellHeaders = new List<string>(); foreach (string sItem in Alphabets)
cellHeaders.Add(sItem); foreach (string item in Alphabets)
foreach (string sItem in Alphabets)
cellHeaders.Add(item + sItem);
} /// <summary>
/// Returns the column caption for the given row & column index.
/// </summary>
/// <param name="rowIndex">Index of the row.</param>
/// <param name="columnIndex">Index of the column.</param>
/// <returns></returns>
internal string Get(int rowIndex, int columnIndex)
{
return this.cellHeaders.ElementAt(columnIndex) + (rowIndex + 1).ToString();
}
} /// <summary>
/// 导出
/// </summary>
/// <param name="DataTable">DataTable</param>
/// <param name="sheetname">工作表名</param>
/// <param name="filename">文件名</param>
/// <returns></returns>
internal string ExportToExcel(DataTable table, string sheetname,string filename)
{
string excelfile = Path.GetTempPath() + filename;
using (SpreadsheetDocument excelDoc = SpreadsheetDocument.Create(excelfile, DocumentFormat.OpenXml.SpreadsheetDocumentType.Workbook))
{
CreateExcelParts(excelDoc, table,sheetname);
}
return excelfile;
}
/// <summary>
///
/// </summary>
/// <param name="spreadsheetDoc"></param>
/// <param name="data"></param>
/// <param name="sheetname"></param>
private void CreateExcelParts(SpreadsheetDocument spreadsheetDoc, DataTable data,string sheetname)
{
WorkbookPart workbookPart = spreadsheetDoc.AddWorkbookPart();
CreateWorkbookPart(workbookPart, sheetname); int workBookPartCount = 1; WorkbookStylesPart workbookStylesPart = workbookPart.AddNewPart<WorkbookStylesPart>("rId" + (workBookPartCount++).ToString());
CreateWorkbookStylesPart(workbookStylesPart); WorksheetPart worksheetPart = workbookPart.AddNewPart<WorksheetPart>("rId" + (101).ToString());
CreateWorksheetPart(workbookPart.WorksheetParts.ElementAt(0), data); SharedStringTablePart sharedStringTablePart = workbookPart.AddNewPart<SharedStringTablePart>("rId" + (workBookPartCount++).ToString());
CreateSharedStringTablePart(sharedStringTablePart, data); workbookPart.Workbook.Save();
} /// <summary>
/// Creates the shared string table part.
/// </summary>
/// <param name="sharedStringTablePart">The shared string table part.</param>
/// <param name="sheetData">The sheet data.</param>
private void CreateSharedStringTablePart(SharedStringTablePart sharedStringTablePart, DataTable sheetData)
{
UInt32Value stringCount = Convert.ToUInt32(sheetData.Rows.Count) + Convert.ToUInt32(sheetData.Columns.Count); SharedStringTable sharedStringTable = new SharedStringTable()
{
Count = stringCount,
UniqueCount = stringCount
}; for (int columnIndex = 0; columnIndex < sheetData.Columns.Count; columnIndex++)
{
SharedStringItem sharedStringItem = new SharedStringItem();
Text text = new Text();
text.Text = sheetData.Columns[columnIndex].ColumnName;
sharedStringItem.Append(text);
sharedStringTable.Append(sharedStringItem);
} for (int rowIndex = 0; rowIndex < sheetData.Rows.Count; rowIndex++)
{
SharedStringItem sharedStringItem = new SharedStringItem();
Text text = new Text();
text.Text = sheetData.Rows[rowIndex][0].ToString();
sharedStringItem.Append(text);
sharedStringTable.Append(sharedStringItem);
} sharedStringTablePart.SharedStringTable = sharedStringTable;
} /// <summary>
/// Creates the worksheet part.
/// </summary>
/// <param name="worksheetPart">The worksheet part.</param>
/// <param name="data">The data.</param>
private void CreateWorksheetPart(WorksheetPart worksheetPart, DataTable data)
{
Worksheet worksheet = new Worksheet() { MCAttributes = new MarkupCompatibilityAttributes() { Ignorable = "x14ac" } };
worksheet.AddNamespaceDeclaration("r", "http://schemas.openxmlformats.org/officeDocument/2006/relationships");
worksheet.AddNamespaceDeclaration("mc", "http://schemas.openxmlformats.org/markup-compatibility/2006");
worksheet.AddNamespaceDeclaration("x14ac", "http://schemas.microsoft.com/office/spreadsheetml/2009/9/ac"); SheetViews sheetViews = new SheetViews();
SheetView sheetView = new SheetView() { WorkbookViewId = (UInt32Value)0U };
Selection selection = new Selection() { ActiveCell = "A1" };
sheetView.Append(selection);
sheetViews.Append(sheetView); PageMargins pageMargins = new PageMargins()
{
Left = 0.7D,
Right = 0.7D,
Top = 0.75D,
Bottom = 0.75D,
Header = 0.3D,
Footer = 0.3D
}; SheetFormatProperties sheetFormatPr = new SheetFormatProperties()
{
DefaultRowHeight = 15D,
DyDescent = 0.25D
}; SheetData sheetData = new SheetData(); UInt32Value rowIndex = 1U; Row row1 = new Row()
{
RowIndex = rowIndex++,
Spans = new ListValue<StringValue>() { InnerText = "1:3" },
DyDescent = 0.25D
}; for (int columnIndex = 0; columnIndex < data.Columns.Count; columnIndex++)
{
Cell cell = new Cell() { CellReference = ExcelHelper.ColumnCaption.Instance.Get((Convert.ToInt32((UInt32)rowIndex) - 2), columnIndex), DataType = CellValues.String };
CellValue cellValue = new CellValue();
cellValue.Text = data.Columns[columnIndex].ColumnName.ToString().FormatCode();
cell.Append(cellValue); row1.Append(cell);
}
sheetData.Append(row1); for (int rIndex = 0; rIndex < data.Rows.Count; rIndex++)
{
Row row = new Row()
{
RowIndex = rowIndex++,
Spans = new ListValue<StringValue>() { InnerText = "1:3" },
DyDescent = 0.25D
}; for (int cIndex = 0; cIndex < data.Columns.Count; cIndex++)
{
if (cIndex == 0)
{
Cell cell = new Cell() { CellReference = ExcelHelper.ColumnCaption.Instance.Get((Convert.ToInt32((UInt32)rowIndex) - 2), cIndex), DataType = CellValues.String };
CellValue cellValue = new CellValue();
cellValue.Text = data.Rows[rIndex][cIndex].ToString();
cell.Append(cellValue); row.Append(cell);
}
else
{
Cell cell = new Cell() { CellReference = ExcelHelper.ColumnCaption.Instance.Get((Convert.ToInt32((UInt32)rowIndex) - 2), cIndex), DataType = CellValues.String };
CellValue cellValue = new CellValue();
cellValue.Text = data.Rows[rIndex][cIndex].ToString();
cell.Append(cellValue); row.Append(cell);
}
}
sheetData.Append(row);
} worksheet.Append(sheetViews);
worksheet.Append(sheetFormatPr);
worksheet.Append(sheetData);
worksheet.Append(pageMargins);
worksheetPart.Worksheet = worksheet;
} /// <summary>
/// Creates the workbook styles part.
/// </summary>
/// <param name="workbookStylesPart">The workbook styles part.</param>
private void CreateWorkbookStylesPart(WorkbookStylesPart workbookStylesPart)
{
Stylesheet stylesheet = new Stylesheet() { MCAttributes = new MarkupCompatibilityAttributes() { Ignorable = "x14ac" } };
stylesheet.AddNamespaceDeclaration("mc", "http://schemas.openxmlformats.org/markup-compatibility/2006");
stylesheet.AddNamespaceDeclaration("x14ac", "http://schemas.microsoft.com/office/spreadsheetml/2009/9/ac"); StylesheetExtensionList stylesheetExtensionList = new StylesheetExtensionList();
StylesheetExtension stylesheetExtension = new StylesheetExtension() { Uri = "{EB79DEF2-80B8-43e5-95BD-54CBDDF9020C}" };
stylesheetExtension.AddNamespaceDeclaration("x14", "http://schemas.microsoft.com/office/spreadsheetml/2009/9/main");
DocumentFormat.OpenXml.Office2010.Excel.SlicerStyles slicerStyles = new DocumentFormat.OpenXml.Office2010.Excel.SlicerStyles() { DefaultSlicerStyle = "SlicerStyleLight1" };
stylesheetExtension.Append(slicerStyles);
stylesheetExtensionList.Append(stylesheetExtension); stylesheet.Append(stylesheetExtensionList); workbookStylesPart.Stylesheet = stylesheet;
} /// <summary>
/// Creates the workbook part.
/// </summary>
/// <param name="workbookPart">The workbook part.</param>
private void CreateWorkbookPart(WorkbookPart workbookPart,string sheetName)
{
Workbook workbook = new Workbook();
Sheets sheets = new Sheets(); Sheet sheet = new Sheet()
{
Name = sheetName, //工作表名
SheetId = Convert.ToUInt32(101),
Id = "rId" + (101).ToString()
};
sheets.Append(sheet); CalculationProperties calculationProperties = new CalculationProperties()
{
CalculationId = (UInt32Value)123456U // some default Int32Value
}; workbook.Append(sheets);
workbook.Append(calculationProperties); workbookPart.Workbook = workbook;
} }
/// <summary>
///
/// </summary>
public static class Extensions
{
public static string FormatCode(this string sourceString)
{
if (sourceString.Contains("<"))
sourceString = sourceString.Replace("<", "<"); if (sourceString.Contains(">"))
sourceString = sourceString.Replace(">", ">"); return sourceString;
}
}

  

 /// <summary>
///
/// </summary>
public partial class WebForm1 : System.Web.UI.Page
{ DataTable getData()
{
DataTable dt = new DataTable();
dt.Columns.Add("id", typeof(int));
dt.Columns.Add("name", typeof(string));
dt.Rows.Add(1, "geovindu");
dt.Rows.Add(2, "geov");
dt.Rows.Add(3, "塗斯博");
dt.Rows.Add(4, "趙雅芝");
dt.Rows.Add(5, " なわち日本語");
dt.Rows.Add(6, "처리한다");
dt.Rows.Add(7, "涂聚文");
dt.Rows.Add(8, "塗聚文");
return dt;
}
/// <summary>
///
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindGrid();
} }
/// <summary>
///
/// </summary>
private void BindGrid()
{
this.GridView1.DataSource = getData();
GridView1.DataBind();
}
/// <summary>
///
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void Button1_Click(object sender, EventArgs e)
{ string rootPath = HttpContext.Current.Server.MapPath("~").ToString();
string localCopy = "塗聚文" + DateTime.Now.ToString("yyyyMMddHHmmssfff")+ ".xlsx"; //
string file = new ExcelHelper().ExportToExcel(getData(), "geovindu",localCopy);
File.Copy(file, rootPath + localCopy);
Response.Redirect(HttpUtility.UrlEncode(localCopy,System.Text.Encoding.UTF8));
}
}

  

        /// <summary>
/// windows 10 Microsoft Edge 测试无效。
///塗聚文註
/// </summary>
/// <param name="dt"></param>
/// <param name="Response"></param>
/// <param name="filename"></param>
public static void Convertexcel(DataTable dt, HttpResponse Response, string filename)
{ //win 10 通不过
Response.Clear();
Response.Buffer = true;
Response.ClearContent();
Response.ClearHeaders();
Response.ContentEncoding = System.Text.Encoding.UTF8;
//Response.AppendHeader("content-disposition", "attachment; filename=myfile.xlsx"); //Response.AddHeader "Content-Disposition", "Attachment;Filename=myfile.csv" //Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
//Response.AddHeader("content-disposition", "attachment;filename=" + System.Web.HttpUtility.UrlEncode(filename, System.Text.Encoding.UTF8) + ".xlsx"); //Response.ContentType = "application/ms-excel"; //application/vnd.ms-excel //2003
//Response.AddHeader("content-disposition", "attachment;filename=" + System.Web.HttpUtility.UrlEncode(filename, System.Text.Encoding.UTF8) + ".xls");//xlsx
Response.Write("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />");
Response.Charset = "utf-8";
Response.Cache.SetCacheability(HttpCacheability.NoCache); //Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";//2007
System.IO.StringWriter stringWrite = new System.IO.StringWriter();
//stringWrite.Encoding
System.Web.UI.HtmlTextWriter htmlWrite = new System.Web.UI.HtmlTextWriter(stringWrite);
//htmlWrite.Encoding
System.Web.UI.WebControls.DataGrid dg = new System.Web.UI.WebControls.DataGrid();
dg.DataSource = dt;
dg.DataBind();
dg.RenderControl(htmlWrite);
string style = @"<!--mce:2-->";
Response.Write(style);
Response.Output.Write(stringWrite.ToString());
//Response.Write(stringWrite.ToString());
Response.Flush();
Response.End();
//HttpContext.Current.ApplicationInstance.CompleteRequest(); }

  http://closedxml.codeplex.com/

http://epplus.codeplex.com/

https://sourceforge.net/projects/closedxmlexcel/

https://github.com/vbjay/ClosedXML

http://stackoverflow.com/questions/23102010/open-xml-reading-from-excel-file

https://openxmlexporttoexcel.codeplex.com/

https://excelpackage.codeplex.com/

https://github.com/OfficeDev/Open-Xml-Sdk

https://openxmlpackaging.codeplex.com/

http://powertools.codeplex.com/

https://github.com/OfficeDev/Open-Xml-PowerTools

http://html2openxml.codeplex.com/

https://github.com/gSerP1983/OpenXml.Excel.Data

https://npoi.codeplex.com/

https://github.com/tonyqus/npoi

csharp: Export DataTable to Excel using OpenXml 2.5 in asp.net的更多相关文章

  1. csharp: Export DataSet into Excel and import all the Excel sheets to DataSet

    /// <summary> /// Export DataSet into Excel /// </summary> /// <param name="send ...

  2. csharp: Export or Import excel using MyXls,Spire.Xls

    excel 2003 (效果不太理想) using System; using System.Collections.Generic; using System.ComponentModel; usi ...

  3. csharp: Export or Import excel using NPOI

    excel 2003: using System; using System.Collections.Generic; using System.ComponentModel; using Syste ...

  4. export DataTable To Excel(C)

          static DataTable GetTable() { DataTable table = new DataTable(); // New data table. table.Colu ...

  5. asp.net DataTable导出Excel 自定义列名

    1.添加引用NPOI.dll 2.cs文件头部添加 using NPOI.HSSF.UserModel; using NPOI.SS.UserModel; using System.IO; 3.代码如 ...

  6. DataTable to Excel(使用NPOI、EPPlus将数据表中的数据读取到excel格式内存中)

    /// <summary> /// DataTable to Excel(将数据表中的数据读取到excel格式内存中) /// </summary> /// <param ...

  7. NetSuite SuiteScript 2.0 export data to Excel file(xls)

    In NetSuite SuiteScript, We usually do/implement export data to CSV, that's straight forward: Collec ...

  8. Datatable导出Excel

    ; IRow headerRow = sheet.CreateRow(); ; ; ; iRowIndex++; } ; i < icolIndex; i++) { sheet.AutoSize ...

  9. 使用Aspose将DataTable转Excel

    0.准备工作   1.下载并引入Aspose.Cells 下载Aspose Cells并引入using Aspose.Cells 下面示例中用的是.net 3.0版本的Aspose Cells,编译环 ...

随机推荐

  1. java 锁3

    先谈线程的状态: 具体来说有, NEW. Running. Blocked.此状态的线程阻塞,它正在等待监视器锁——等待另外一个线程释放锁(通俗说就是等它执行完synchronized了的方法/代码块 ...

  2. 如何在 Ubuntu 15.04 上安装带 JSON 支持的 SQLite 3.9

    欢迎阅读我们关于SQLite 的文章,SQLite 是当今世界上使用最广泛的 SQL 数据库引擎,它基本不需要配置,不需要设置或管理就可以运行.SQLite 是一个是公开领域(public-domai ...

  3. EF架构~数据分批批量提交

    回到目录 对于大数据量提交,包括插入,更新和删除,我始终不建议用EF自带的方法,因为它会增加与数据库的交互次数,一般地,EF的一个上下文在提交时会打开一个数据连接,然后把转换成的SQL语句一条一条的发 ...

  4. C#教程(1) -- .Net与C#简介

    (1).Net .Net指.Net平台或者是.Net Framework框架. 如果你把.Net平台想象成一个厨房,那么.Net Framework框架就是其中的柴米油盐酱醋茶. 如果你把.Net平台 ...

  5. Java-map-第一题 (Map)利用Map,完成下面的功能: 从命令行读入一个字符串,表示一个年份,输出该年的世界杯冠军是哪支球队。如果该 年没有举办世界杯,则输出:没有举办世界杯。 附:世界杯冠军以及对应的夺冠年份,请参考本章附录。 附录

    第一题 (Map)利用Map,完成下面的功能: 从命令行读入一个字符串,表示一个年份,输出该年的世界杯冠军是哪支球队.如果该 年没有举办世界杯,则输出:没有举办世界杯. 附:世界杯冠军以及对应的夺冠年 ...

  6. JavaScript 模板引擎实现原理解析

    1.入门实例 首先我们来看一个简单模板: <script type="template" id="template"> <h2> < ...

  7. WEBAPP开发技巧(手机网站开发注意事项)

    以下只是我个人得总结,如果你有更好的建议,请留言,一起共勉进步!!- -! 1.要响应式开发web,也就是页面必须自适应屏幕大小,可以采用流体布局,如之前的文章(自适应宽度布局),其他具体的小问题可以 ...

  8. javase基础复习攻略《二》

    今天就开始的真正走进JAVASE的世界,本篇介绍的是:JAVASE基础语法,大家如果有C语言的基础,对于本节内容一定感觉非常轻松,编程语言之间的都是相通的,只不过C语言属于面向过程编程,而JAVA语言 ...

  9. SQL 语句中union all和order by同时使用

            最近做的一个财物管理系统中查询过期或逾期的存储过程,返回 “财物所属的案件名称”,“财物名称”,“财物编号”,“过期或逾期时间”(超期或逾期前7天开始预警). 遇到“union all ...

  10. 基于Metronic的Bootstrap开发框架经验总结(4)--Bootstrap图标的提取和利用

    在前面的一篇随笔<基于Metronic的Bootstrap开发框架经验总结(1)-框架总览及菜单模块的处理>介绍了菜单模块的处理,主要介绍如何动态从数据库里面获取记录并构建菜单列表.其中菜 ...