因为我使用wpf简单写的一个Demo,我会将代码全部都写在这里面,里面有的地方有些乱,慢慢的再去整理,里面可能有参考其他人整理的代码,参考过来的!希望对大家有帮助
下面是MainWindow.xaml文件
<Window x:Class="_004ExportExcelDemo.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525">
<Grid>
<ListView x:Name="lv" HorizontalAlignment="Left" Height="273" Margin="10,10,0,0" VerticalAlignment="Top" Width="497">
<ListView.View>
<GridView>
<GridViewColumn Width="50" Header="序号" DisplayMemberBinding="{Binding Index}"/>
<GridViewColumn Width="100" Header="学号" DisplayMemberBinding="{Binding Id}"/>
<GridViewColumn Width="100" Header="姓名" DisplayMemberBinding="{Binding Name}"/>
<GridViewColumn Width="50" Header="成绩" DisplayMemberBinding="{Binding Score}"/>
<GridViewColumn Width="100" Header="学科" DisplayMemberBinding="{Binding Subject}"/>
<GridViewColumn Width="100" Header="备注" DisplayMemberBinding="{Binding Remark}"/>
</GridView>
</ListView.View>
</ListView>
<Button Content="导出" HorizontalAlignment="Left" Margin="412,288,0,0" VerticalAlignment="Top" Width="95" RenderTransformOrigin="0.628,-0.37" Height="22" Click="Button_Click"/>
</Grid>
</Window>
下面是MainWindow.xaml.cs
using _004ExportExcelDemo.Models;
using System.Collections.Generic;
using System.Data;
using System.Windows;
namespace _004ExportExcelDemo
{
/// <summary>
/// MainWindow.xaml 的交互逻辑
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
this.Loaded += MainWindow_Loaded;
}
private void MainWindow_Loaded(object sender, RoutedEventArgs e)
{
var list = new List<StudentModel>
{
new StudentModel{Index = 1, Id = "2013030001", Name = "梁志伟", Subject = "数学", Score = 95, Remark = "不错"},
new StudentModel{Index = 2, Id = "2013030002", Name = "丁纪明", Subject = "数学", Score = 92, Remark = "不错"},
new StudentModel{Index = 3, Id = "2013030003", Name = "舒伟琪", Subject = "数学", Score = 97, Remark = "不错"},
new StudentModel{Index = 4, Id = "2013030004", Name = "王涛", Subject = "数学", Score = 88, Remark = "不错"},
new StudentModel{Index = 5, Id = "2013030005", Name = "贾晓鹏", Subject = "数学", Score = 90, Remark = "不错"},
new StudentModel{Index = 6, Id = "2013030006", Name = "徐菲", Subject = "数学", Score = 95, Remark = "不错"},
};
this.lv.ItemsSource = null;
this.lv.ItemsSource = list;
}
private void Button_Click(object sender, RoutedEventArgs e)
{
var list = this.lv.ItemsSource as List<StudentModel>;
System.Windows.Forms.SaveFileDialog sfd = new System.Windows.Forms.SaveFileDialog();
sfd.FileName = "导出内容.xls";
sfd.Filter = "*.xls|";
if (sfd.ShowDialog() != System.Windows.Forms.DialogResult.OK)
return;
Export(list, sfd.FileName);
}
private void Export(List<StudentModel> list, string path)
{
var dt = new DataTable();
dt.Columns.Add("序号");
dt.Columns.Add("编号");
dt.Columns.Add("姓名");
dt.Columns.Add("学科");
dt.Columns.Add("成绩");
dt.Columns.Add("备注");
foreach (var item in list)
{
DataRow row = dt.NewRow();
row[0] = item.Index;
row[1] = item.Id;
row[2] = item.Name;
row[3] = item.Subject;
row[4] = item.Score;
row[5] = item.Remark;
dt.Rows.Add(row);
}
NPOIExportExcelHelper.Instance.Export(dt, "", path);
MessageBox.Show("导出成功!");
}
}
}
这里面实体就不写在里面了,下面是导出的操作
using System.Data;
using System.IO;
using System.Text;
using NPOI.HPSF;
using NPOI.HSSF.UserModel;
using System;
using NPOI.SS.Util;
namespace _004ExportExcelDemo
{
public class NPOIExportExcelHelper
{
private static NPOIExportExcelHelper _instance;
public static NPOIExportExcelHelper Instance
{
get
{
if (_instance == null)
{
_instance = new NPOIExportExcelHelper();
}
return NPOIExportExcelHelper._instance;
}
}
/// <summary>
/// DataTable导出到Excel文件
/// </summary>
/// <param name="dtSource">源DataTable</param>
/// <param name="strHeaderText">表头文本</param>
/// <param name="strFileName">保存位置</param>
public void Export(DataTable dtSource, string strHeaderText, string strFileName)
{
using (MemoryStream ms = Export(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>
/// DataTable导出到Excel的MemoryStream
/// </summary>
/// <param name="dtSource">源DataTable</param>
/// <param name="strHeaderText">表头文本</param>
public MemoryStream Export(DataTable dtSource, string strHeaderText)
{
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = (HSSFSheet)workbook.CreateSheet();
#region 右击文件 属性信息
{
DocumentSummaryInformation dsi = PropertySetFactory.CreateDocumentSummaryInformation();
dsi.Company = "瑞杰";
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 = DateTime.Now;
workbook.SummaryInformation = si;
}
#endregion
HSSFCellStyle dateStyle = (HSSFCellStyle)workbook.CreateCellStyle();
HSSFDataFormat format = (HSSFDataFormat)workbook.CreateDataFormat();
dateStyle.DataFormat = format.GetFormat("yyyy-mm-dd");
dateStyle.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Center;
HSSFCellStyle CommonStyle = (HSSFCellStyle)workbook.CreateCellStyle();
CommonStyle.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Center;
//取得列宽
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 = NPOI.SS.UserModel.HorizontalAlignment.Center;
HSSFFont font = (HSSFFont)workbook.CreateFont();
font.FontHeightInPoints = 20;
font.Boldweight = 00;
headStyle.SetFont(font);
headerRow.GetCell(0).CellStyle = headStyle;
sheet.AddMergedRegion(new Region(0, 0, 0, dtSource.Columns.Count - 1));
}
#endregion
#region 列头及样式
{
HSSFRow headerRow = (HSSFRow)sheet.CreateRow(1);
HSSFCellStyle headStyle = (HSSFCellStyle)workbook.CreateCellStyle();
headStyle.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Center;
HSSFFont font = (HSSFFont)workbook.CreateFont();
font.FontHeightInPoints = 12;
font.Boldweight = 400;
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);
newCell.CellStyle = CommonStyle;//普通样式
break;
case "System.DateTime"://日期类型
DateTime dateV;
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);
newCell.CellStyle = CommonStyle;//普通样式
break;
case "System.Int16"://整型
case "System.Int32":
case "System.Int64":
case "System.Byte":
int intV = 0;
int.TryParse(drValue, out intV);
newCell.SetCellValue(intV);
newCell.CellStyle = CommonStyle;//普通样式
break;
case "System.Decimal"://浮点型
case "System.Double":
double doubV = 0;
double.TryParse(drValue, out doubV);
newCell.SetCellValue(doubV);
newCell.CellStyle = CommonStyle;//普通样式
break;
case "System.DBNull"://空值处理
newCell.SetCellValue("");
newCell.CellStyle = CommonStyle;//普通样式
break;
default:
newCell.SetCellValue("");
newCell.CellStyle = CommonStyle;//普通样式
break;
}
}
#endregion
rowIndex++;
}
using (MemoryStream ms = new MemoryStream())
{
workbook.Write(ms);
ms.Flush();
ms.Position = 0;
//sheet.Dispose();
//workbook.Dispose();//一般只用写这一个就OK了,他会遍历并释放所有资源,但当前版本有问题所以只释放sheet
return ms;
}
}
}
}
http://download.csdn.net/download/l_zhiwei/10207690