OpenXmlSdk导出Excel
感觉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的更多相关文章
- .NET导出Excel的四种方法及评测
.NET导出Excel的四种方法及评测 导出Excel是.NET的常见需求,开源社区.市场上,都提供了不少各式各样的Excel操作相关包.本文,我将使用NPOI.EPPlus.OpenXML.Aspo ...
- [转帖].NET导出Excel的四种方法及评测
.NET导出Excel的四种方法及评测 https://www.cnblogs.com/sdflysha/p/20190824-dotnet-excel-compare.html 导出Excel是.N ...
- C#使用Aspose.Cells导出Excel简单实现
首先,需要添加引用Aspose.Cells.dll,官网下载地址:http://downloads.aspose.com/cells/net 将DataTable导出Xlsx格式的文件下载(网页输出) ...
- 利用poi导出Excel
import java.lang.reflect.Field;import java.lang.reflect.InvocationTargetException;import java.lang.r ...
- [django]数据导出excel升级强化版(很强大!)
不多说了,原理采用xlwt导出excel文件,所谓的强化版指的是实现在网页上选择一定条件导出对应的数据 之前我的博文出过这类文章,但只是实现导出数据,这次左思右想,再加上网上的搜索,终于找出方法实现条 ...
- NPOI导出Excel
using System;using System.Collections.Generic;using System.Linq;using System.Text;#region NPOIusing ...
- ASP.NET Core 导入导出Excel xlsx 文件
ASP.NET Core 使用EPPlus.Core导入导出Excel xlsx 文件,EPPlus.Core支持Excel 2007/2010 xlsx文件导入导出,可以运行在Windows, Li ...
- asp.net DataTable导出Excel 自定义列名
1.添加引用NPOI.dll 2.cs文件头部添加 using NPOI.HSSF.UserModel; using NPOI.SS.UserModel; using System.IO; 3.代码如 ...
- Aspose.Cells导出Excel(1)
利用Aspose.Cells导出excel 注意的问题 1.DataTable的处理 2.进行编码,便于中文名文件下载 3.别忘了Aspose.Cells.dll(可以自己在网上搜索) public ...
随机推荐
- you don't have permission 错误
当引入第三方的框架的时候 容易产生以下问题: The file “XXX.app” couldn’t be opened because you don’t have permission to vi ...
- Yaroslav and Divisors
Codeforces Round #182 (Div. 1) D:http://codeforces.com/contest/301/problem/D 题意:给一个1-n,n个数的序列,然后查询一个 ...
- Arrays常用API的事例
import java.util.ArrayList;import java.util.Arrays;import java.util.List; public class TestArrays { ...
- strtotime的几种用法区别
strtotime不仅可以使用类似Y-m-d此类标准的时间/日期字符串来转化时间戳, 还可以用类似自然语言的来生成时间戳, 类似: strtotime('last day'); strtotime(' ...
- Alignment ( 最长上升(下降)子序列 )
Time Limit: 1000MS Memory Limit: 30000K Total Submissions: 11397 Accepted: 3630 Description In t ...
- 「Poetize5」Vani和Cl2捉迷藏
描述 Description 这片树林里有N座房子,M条有向道路,组成了一张有向无环图.树林里的树非常茂密,足以遮挡视线,但是沿着道路望去,却是视野开阔.如果从房子A沿着路走下去能够到达B,那么在A和 ...
- 【转】ConcurrentModificationException异常解决办法 --不错
原文网址:http://blog.sina.com.cn/s/blog_465bcfba01000ds7.html 1月30日java.util.ConcurrentModificationExcep ...
- 【转】Android低功耗蓝牙应用开发获取的服务UUID
原文网址:http://blog.csdn.net/zhangjs0322/article/details/39048939 Android低功耗蓝牙应用程序开始时获取到的蓝牙血压计所有服务的UUID ...
- 【最短路】Vijos P1022Victoria的舞会2
题目链接: https://vijos.org/p/1022 题目大意: 给一张N个点的有向图,求有几块强连通分量.(N<=200) 题目思路: [动态规划] n比较小,可以用floyd暴力把每 ...
- Evaluate Reverse Polish Notation——LeetCode
Evaluate the value of an arithmetic expression in Reverse Polish Notation. Valid operators are +, -, ...