感觉OpenXmlSdk的语法真的不是很友好。研究了半天,只实现了简单的导出功能。对于单元格样式的设置暂时还是搞明白,网上的资料真的很少,官方文档是英文的。中文的文章大都是用工具(Open XML SDK 2.0 Productivity Tool)搞出来的,反正在我这是不管用。最终还是回到了NPOI 的怀抱。

  最后还是把这点代码记录一下,以后有时间再继续研究吧。

 using System;
using System.Data;
using System.IO;
using System.Web;
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Spreadsheet; public static class ExportHelper
{
/// <summary>
/// 导出Excel文件
/// </summary>
/// <param name="fileName"></param>
/// <param name="dataSet">DataSet中每个DataTable生成一个Sheet</param>
public static void ExportExcel(string fileName, DataSet dataSet)
{
if (dataSet.Tables.Count == )
{
return;
} using (MemoryStream stream = DataTable2ExcelStream(dataSet))
{
FileStream fs = new FileStream(fileName, FileMode.CreateNew);
stream.WriteTo(fs);
fs.Flush();
fs.Close();
}
} public static void ExportExcel(string fileName, DataTable dataTable)
{
DataSet dataSet = new DataSet();
dataSet.Tables.Add(dataTable);
ExportExcel(fileName, dataSet);
} /// <summary>
/// Web导出Excel文件
/// </summary>
/// <param name="fileName"></param>
/// <param name="dataSet">DataSet中每个DataTable生成一个Sheet</param>
public static void ResponseExcel(string fileName, DataSet dataSet)
{
if (dataSet.Tables.Count == )
{
return;
} using (MemoryStream stream = DataTable2ExcelStream(dataSet))
{
ExportExcel(fileName, stream);
}
} public static void ResponseExcel(string fileName, DataTable dataTable)
{
DataSet dataSet = new DataSet();
dataSet.Tables.Add(dataTable.Copy());
ResponseExcel(fileName, dataSet);
} private static void ExportExcel(string fileName, MemoryStream stream)
{
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.Charset = "UTF-8";
HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename= " + HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8));
HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.UTF8;
HttpContext.Current.Response.ContentType = "application/ms-excel";
HttpContext.Current.Response.BinaryWrite(stream.ToArray());
HttpContext.Current.Response.Flush();
HttpContext.Current.Response.End();
} private static MemoryStream DataTable2ExcelStream(DataSet dataSet)
{
MemoryStream stream = new MemoryStream();
SpreadsheetDocument document = SpreadsheetDocument.Create(stream,
SpreadsheetDocumentType.Workbook); WorkbookPart workbookPart = document.AddWorkbookPart();
workbookPart.Workbook = new Workbook(); Sheets sheets = document.WorkbookPart.Workbook.AppendChild(new Sheets()); for (int i = ; i < dataSet.Tables.Count; i++)
{
DataTable dataTable = dataSet.Tables[i];
WorksheetPart worksheetPart = document.WorkbookPart.AddNewPart<WorksheetPart>();
worksheetPart.Worksheet = new Worksheet(new SheetData()); Sheet sheet = new Sheet
{
Id = document.WorkbookPart.GetIdOfPart(worksheetPart),
SheetId = (UInt32)(i + ),
Name = dataTable.TableName
};
sheets.Append(sheet); SheetData sheetData = worksheetPart.Worksheet.GetFirstChild<SheetData>(); Row headerRow = CreateHeaderRow(dataTable.Columns);
sheetData.Append(headerRow); for (int j = ; j < dataTable.Rows.Count; j++)
{
sheetData.Append(CreateRow(dataTable.Rows[j], j + ));
}
} document.Close(); return stream;
} private static Row CreateHeaderRow(DataColumnCollection columns)
{
Row header = new Row();
for (int i = ; i < columns.Count; i++)
{
Cell cell = CreateCell(i + , , columns[i].ColumnName, CellValues.String);
header.Append(cell);
}
return header;
} private static Row CreateRow(DataRow dataRow, int rowIndex)
{
Row row = new Row();
for (int i = ; i < dataRow.Table.Columns.Count; i++)
{
Cell cell = CreateCell(i + , rowIndex, dataRow[i], GetType(dataRow.Table.Columns[i].DataType));
row.Append(cell);
}
return row;
} private static CellValues GetType(Type type)
{
if (type == typeof(decimal))
{
return CellValues.Number;
}
//if ((type == typeof(DateTime)))
//{
// return CellValues.Date;
//}
return CellValues.SharedString;
} private static Cell CreateCell(int columnIndex, int rowIndex, object cellValue, CellValues cellValues)
{
Cell cell = new Cell
{
CellReference = GetCellReference(columnIndex) + rowIndex,
CellValue = new CellValue { Text = cellValue.ToString() },
DataType = new EnumValue<CellValues>(cellValues),
StyleIndex =
};
return cell;
} private static string GetCellReference(int colIndex)
{
int dividend = colIndex;
string columnName = String.Empty; while (dividend > )
{
int modifier = (dividend - ) % ;
columnName = Convert.ToChar( + modifier) + columnName;
dividend = (dividend - modifier) / ;
} return columnName;
}
}

OpenXmlSdk导出Excel的更多相关文章

  1. .NET导出Excel的四种方法及评测

    .NET导出Excel的四种方法及评测 导出Excel是.NET的常见需求,开源社区.市场上,都提供了不少各式各样的Excel操作相关包.本文,我将使用NPOI.EPPlus.OpenXML.Aspo ...

  2. [转帖].NET导出Excel的四种方法及评测

    .NET导出Excel的四种方法及评测 https://www.cnblogs.com/sdflysha/p/20190824-dotnet-excel-compare.html 导出Excel是.N ...

  3. C#使用Aspose.Cells导出Excel简单实现

    首先,需要添加引用Aspose.Cells.dll,官网下载地址:http://downloads.aspose.com/cells/net 将DataTable导出Xlsx格式的文件下载(网页输出) ...

  4. 利用poi导出Excel

    import java.lang.reflect.Field;import java.lang.reflect.InvocationTargetException;import java.lang.r ...

  5. [django]数据导出excel升级强化版(很强大!)

    不多说了,原理采用xlwt导出excel文件,所谓的强化版指的是实现在网页上选择一定条件导出对应的数据 之前我的博文出过这类文章,但只是实现导出数据,这次左思右想,再加上网上的搜索,终于找出方法实现条 ...

  6. NPOI导出Excel

    using System;using System.Collections.Generic;using System.Linq;using System.Text;#region NPOIusing ...

  7. ASP.NET Core 导入导出Excel xlsx 文件

    ASP.NET Core 使用EPPlus.Core导入导出Excel xlsx 文件,EPPlus.Core支持Excel 2007/2010 xlsx文件导入导出,可以运行在Windows, Li ...

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

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

  9. Aspose.Cells导出Excel(1)

    利用Aspose.Cells导出excel 注意的问题 1.DataTable的处理 2.进行编码,便于中文名文件下载 3.别忘了Aspose.Cells.dll(可以自己在网上搜索) public ...

随机推荐

  1. temp 临时文件

    放假了,放假了:http://blog.csdn.net/skywalker_only/article/details/17076851 nucht2.2.1爆出如下异常: Exception in ...

  2. BZOJ 3243 向量内积

    Description 两个\(d\)维向量\(A=[a_{1},a_{2},...,a_{d}]\)与\(B=[b_{1},b_{2},...,b_{d}]\)的内积为其相对应维度的权值的乘积和,即 ...

  3. HAPROXY实习

    没事玩玩,简单搞定. 同一个URL可以分发到后端不同的WEB上. STATS页画也刷出来了. 参考网址: http://www.cnblogs.com/kgdxpr/p/3272861.html 如果 ...

  4. DB2中的系统表SYSIBM.SYSDUMMY1

    ORACLE中有一张系统数据库表DUAL用来访问系统的相关信息 SELECT SYSDATE FROM DUAL;  --返回当前系统日期 ------------------------------ ...

  5. c#分支语句;循环语句(随堂练习)

    1. 输入月份,日期号,输出是今年的第几天    平年,2月28天     switch (变量名) {case "": break} 2. 循环语句:    for(int i ...

  6. nginx 1.3.9/1.4.0 x86 Brute Force Remote Exploit

    测试方法: 本站提供程序(方法)可能带有攻击性,仅供安全研究与教学之用,风险自负! #nginx 1.3.9/1.4.0 x86 brute force remote exploit # copyri ...

  7. Xmanager4使用记录

    想在windows下远程登录到了Linux桌面,但又不想装vnc server,况且根据同学的实践,vnc的桌面在远程和本地都能看得到,这个似乎不太好.   google到xmanager,装了个测试 ...

  8. 数据结构(堆):POJ 1442 Black Box

    Black Box Time Limit: 1000MS   Memory Limit: 10000K Total Submissions: 10658   Accepted: 4390 Descri ...

  9. 数据结构(主席树):HDU 4729 An Easy Problem for Elfness

    An Easy Problem for Elfness Time Limit: 5000/2500 MS (Java/Others)    Memory Limit: 65535/65535 K (J ...

  10. Android公共库——图片缓存 网络缓存 下拉及底部更多ListView 公共类

    Android公共库——图片缓存 网络缓存 下拉及底部更多ListView 公共类 转载自http://www.trinea.cn/android/android-common-lib/ 介绍总结的一 ...