提交 4eb08b61 编写于 作者: 小时後可胖了's avatar 小时後可胖了

Signed-off-by: 柯勇 <1678167865@qq.com>

上级 f7774749
...@@ -2,5 +2,12 @@ ...@@ -2,5 +2,12 @@
# 此 .gitignore 文件已由 Microsoft(R) Visual Studio 自动创建。 # 此 .gitignore 文件已由 Microsoft(R) Visual Studio 自动创建。
################################################################################ ################################################################################
/NPOI_Project/bin/Debug/netcoreapp3.1 /ExcelExport/.vs/ExcelExport
/NPOI_Project/obj /ExcelExport/Excel.Export.Data/bin/Debug/netcoreapp3.1
/ExcelExport/Excel.Export.Data/obj
/ExcelExport/ExcelExport.Base/obj
/ExcelExport/ExcelExport.Base/bin/Debug/netcoreapp3.1
/ExcelExport/ExcelExport.Export/bin/Debug/netcoreapp3.1
/ExcelExport/ExcelExport.Export/obj
/ExcelExport/ExcelExport.UI/bin/Debug/netcoreapp3.1
/ExcelExport/ExcelExport.UI/obj
<?xml version="1.0" ?> <?xml version="1.0" ?>
<root> <root>
<database>数据库:国际数据主要国家(地区)年度数据</database> <database>国际数据主要国家(地区)年度数据</database>
<data> <data>
<record> <record>
<field name="指标">年中人口(人)</field> <field name="指标">年中人口(人)</field>
......
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netcoreapp3.1</TargetFramework>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\ExcelExport.Base\ExcelExport.Base.csproj" />
</ItemGroup>
<ItemGroup>
<None Update="DataFiles\国际数据主要国家%28地区%29年度数据.xml">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
</ItemGroup>
</Project>
using System; using ExcelExport.Base;
using System;
using System.Data; using System.Data;
using System.IO; using System.IO;
using System.Xml; using System.Xml;
namespace NPOI_Project.Helper namespace Excel.Export.Data
{ {
public class XmlHelper public class XmlData : IData
{ {
private static readonly string XmlRoot = AppDomain.CurrentDomain.BaseDirectory + "/Data/"; private static readonly string XmlRoot = AppDomain.CurrentDomain.BaseDirectory + "DataFiles/";
public DataTable GetTableData(string fileName)
public static DataTable WriteToTable(string fileName)
{ {
fileName = XmlRoot + fileName; fileName = XmlRoot + fileName;
if (!File.Exists(fileName)) if (!File.Exists(fileName))
......
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netcoreapp3.1</TargetFramework>
</PropertyGroup>
</Project>
using System;
using System.Collections.Generic;
using System.Data;
using System.Text;
namespace ExcelExport.Base
{
public interface IData
{
public DataTable GetTableData(string path);
}
}
using System;
using System.Data;
namespace ExcelExport.Base
{
public interface IExport
{
public bool Export(DataTable dt, string filenPath);
public bool Export(DataSet ds, string filePath);
}
}
namespace ExcelExport.Base
{
public class ModelBase
{
}
}
using ExcelExport.Base;
using OfficeOpenXml;
using OfficeOpenXml.Drawing.Chart;
using OfficeOpenXml.Style;
using System;
using System.Data;
using System.Drawing;
using System.IO;
namespace ExcelExport.Export
{
public class EPPlusExport : IExport
{
static EPPlusExport()
{
//EPPlus 5.0 以后的版本需要指定 商业证书 或者非商业证书。你需要在代码里指定证书或者降低EPPlus版本
ExcelPackage.LicenseContext = LicenseContext.NonCommercial;
}
public bool Export(DataTable dt, string filenPath)
{
DataSet ds = new DataSet();
ds.Tables.Add(dt.Copy());
return Export(ds, filenPath);
}
public bool Export(DataSet ds, string filePath)
{
using ExcelPackage package = new ExcelPackage();
foreach (DataTable item in ds.Tables)
{
if (!Export(item, package))
{
return false;
}
}
byte[] bytes = package.GetAsByteArray();
FileStream fs = new FileStream(filePath, FileMode.Create, FileAccess.Write);
fs.Write(bytes, 0, bytes.Length);
fs.Flush();
fs.Close();
return true;
}
private bool Export(DataTable dt, ExcelPackage package)
{
if (package is null)
return false;
ExcelWorksheet sheet = package.Workbook.Worksheets.Add(dt.TableName);
//设置标题样式
var caption = sheet.Cells[1, 1];
caption.Value = dt.TableName;
caption.Style.VerticalAlignment = ExcelVerticalAlignment.Center;
caption.Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;
caption.Style.Font.Size = 16;
caption.Style.Font.Bold = true;
sheet.Cells[1, 1, 1, dt.Columns.Count].Merge = true;//合并单元格
sheet.Cells[1, 1, 1, dt.Columns.Count].Style.Border.BorderAround(ExcelBorderStyle.Thin, Color.Black);
//设置列头
sheet.Row(2).Height = 30;
for (int i = 0; i < dt.Columns.Count; i++)
{
var head = sheet.Cells[2, i + 1];
head.Value = dt.Columns[i];
head.Style.Border.BorderAround(ExcelBorderStyle.Thin, Color.Black);
head.Style.Fill.PatternType = ExcelFillStyle.Solid;
head.Style.Fill.BackgroundColor.SetColor(Color.Gold);
head.Style.VerticalAlignment = ExcelVerticalAlignment.Center;
head.Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;
sheet.Column(i + 1).Width = 20;//设置列宽
}
//填充数据
for (int i = 0; i < dt.Rows.Count; i++)
{
sheet.Row(i + 3).Height = 30;//设置行高
for (int j = 0; j < dt.Columns.Count; j++)
{
var cell = sheet.Cells[i + 3, j + 1];
if (j == 3)
cell.Value = Convert.ToDouble(dt.Rows[i][j]);
else
cell.Value = dt.Rows[i][j];
cell.Style.Border.BorderAround(ExcelBorderStyle.Thin, Color.Black);
cell.Style.VerticalAlignment = ExcelVerticalAlignment.Center;
cell.Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;
}
}
ExcelChart chart = sheet.Drawings.AddChart("chart", eChartType.BarStacked);
ExcelChartSerie serie = chart.Series.Add(sheet.Cells[3, 4, 9, 4], sheet.Cells[3, 2, 9, 3]);
serie.Header = "2017年";
chart.SetPosition(100, 600);//设置位置
chart.SetSize(800, 400);//设置大小
chart.Title.Text = "国际数据主要国家年度数据";//设置图表的标题
//chart.Title.Font.Color = Color.FromArgb(89, 89, 89);//设置标题的颜色
chart.Title.Font.Size = 15;//标题的大小
chart.Title.Font.Bold = true;//标题的粗体
chart.Style = eChartStyle.Style15;//设置图表的样式
chart.Legend.Border.LineStyle = OfficeOpenXml.Drawing.eLineStyle.Solid;
chart.Legend.Border.Fill.Color = Color.FromArgb(217, 217, 217);//设置图例的样式
package.Save();
//sheet.Cells.Style.ShrinkToFit = true;//单元格自动适应大小
//sheet.Row(1).CustomHeight = true;//自动调整行高
//sheet.Column(1).Width = 30;//设置列宽
return true;
}
}
}
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netcoreapp3.1</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="EPPlus" Version="5.7.4" />
<PackageReference Include="NPOI" Version="2.5.4" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\ExcelExport.Base\ExcelExport.Base.csproj" />
</ItemGroup>
</Project>
using NPOI.HSSF.UserModel; using ExcelExport.Base;
using NPOI.HSSF.UserModel;
using NPOI.HSSF.Util; using NPOI.HSSF.Util;
using NPOI.SS.UserModel; using NPOI.SS.UserModel;
using System.Data; using System.Data;
using System.IO; using System.IO;
namespace NPOI_Project.NpoiHelper namespace ExcelExport.Export
{ {
public class ExcelHelper public class NPOIExport : IExport
{ {
public bool Export(DataTable dt, string filePath)
{
HSSFWorkbook sheets = Export(dt);
return ExportToFile(sheets, filePath);
}
public bool Export(DataSet ds, string filePath)
{
HSSFWorkbook sheets = new HSSFWorkbook();
foreach (DataTable item in ds.Tables)
{
Export(item, sheets);
}
return ExportToFile(sheets, filePath);
}
private static HSSFWorkbook Export(DataTable dt, HSSFWorkbook sheets = null) private static HSSFWorkbook Export(DataTable dt, HSSFWorkbook sheets = null)
{ {
if (sheets is null) if (sheets is null)
...@@ -21,7 +38,7 @@ namespace NPOI_Project.NpoiHelper ...@@ -21,7 +38,7 @@ namespace NPOI_Project.NpoiHelper
caption.CellStyle.FillForegroundColor = HSSFColor.White.Index; caption.CellStyle.FillForegroundColor = HSSFColor.White.Index;
caption.SetCellValue(dt.TableName); caption.SetCellValue(dt.TableName);
//合并单元格 //合并单元格
sheet.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(0, 0, 0, dt.Columns.Count-1)); sheet.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(0, 0, 0, dt.Columns.Count - 1));
//添加列数据 //添加列数据
var headler = sheet.CreateRow(1); var headler = sheet.CreateRow(1);
ICellStyle cellStyle = GetStyle(sheets); ICellStyle cellStyle = GetStyle(sheets);
...@@ -46,22 +63,6 @@ namespace NPOI_Project.NpoiHelper ...@@ -46,22 +63,6 @@ namespace NPOI_Project.NpoiHelper
return sheets; return sheets;
} }
public static bool Export(DataTable dt, string filePath)
{
HSSFWorkbook sheets = Export(dt);
return ExportToFile(sheets, filePath);
}
public static bool Export(DataSet ds, string filepath)
{
HSSFWorkbook sheets = new HSSFWorkbook();
foreach (DataTable item in ds.Tables)
{
Export(item, sheets);
}
return ExportToFile(sheets, filepath);
}
private static bool ExportToFile(HSSFWorkbook sheets, string filepath) private static bool ExportToFile(HSSFWorkbook sheets, string filepath)
{ {
try try
...@@ -79,7 +80,6 @@ namespace NPOI_Project.NpoiHelper ...@@ -79,7 +80,6 @@ namespace NPOI_Project.NpoiHelper
{ {
return false; return false;
} }
} }
private static ICellStyle GetStyle(HSSFWorkbook sheets, bool isHaed = false) private static ICellStyle GetStyle(HSSFWorkbook sheets, bool isHaed = false)
......
<Application x:Class="NPOI_Project.App" <Application x:Class="ExcelExport.UI.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:NPOI_Project" xmlns:local="clr-namespace:ExcelExport.UI"
StartupUri="MainWindow.xaml"> StartupUri="MainWindow.xaml">
<Application.Resources> <Application.Resources>
<ResourceDictionary Source="pack://application:,,,/SmartUI;component/Themes/Default.xaml" /> <ResourceDictionary Source="pack://application:,,,/SmartUI;component/Themes/Default.xaml" />
......
...@@ -6,7 +6,7 @@ using System.Linq; ...@@ -6,7 +6,7 @@ using System.Linq;
using System.Threading.Tasks; using System.Threading.Tasks;
using System.Windows; using System.Windows;
namespace NPOI_Project namespace ExcelExport.UI
{ {
/// <summary> /// <summary>
/// Interaction logic for App.xaml /// Interaction logic for App.xaml
......
...@@ -7,18 +7,12 @@ ...@@ -7,18 +7,12 @@
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="NPOI" Version="2.5.4" /> <PackageReference Include="SmartUI" Version="1.0.1.5" />
<PackageReference Include="SmartUI" Version="1.0.1.4" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<Folder Include="Services\" /> <ProjectReference Include="..\Excel.Export.Data\Excel.Export.Data.csproj" />
</ItemGroup> <ProjectReference Include="..\ExcelExport.Export\ExcelExport.Export.csproj" />
<ItemGroup>
<None Update="Data\国际数据主要国家%28地区%29年度数据.xml">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
</ItemGroup> </ItemGroup>
</Project> </Project>
<Window x:Class="ExcelExport.UI.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"
xmlns:local="clr-namespace:ExcelExport.UI"
mc:Ignorable="d"
xmlns:smart="clr-namespace:SmartUI.Controls;assembly=SmartUI"
Title="Excel导出" Height="700" Width="1200" WindowStartupLocation="CenterScreen">
<DockPanel LastChildFill="True">
<StackPanel Orientation="Horizontal" DockPanel.Dock="Top" HorizontalAlignment="Right">
<TextBlock Text="导出方式:" FontSize="16"/>
<smart:ComboBoxControl x:Name="combox" Margin="10 0" >
<ComboBoxItem Content="NPOI" IsSelected="True"/>
<ComboBoxItem Content="EPPlus"/>
</smart:ComboBoxControl>
<Button Content="导出" x:Name="exportBtn" Cursor="Hand" Width="150" Style="{StaticResource PrimaryButtonStyle1}" HorizontalAlignment="Right"/>
</StackPanel>
<DataGrid x:Name="dt" AutoGenerateColumns="True"/>
</DockPanel>
</Window>
using NPOI_Project.Helper; using Excel.Export.Data;
using NPOI_Project.NpoiHelper; using ExcelExport.Base;
using ExcelExport.Export;
using System; using System;
using System.Collections.Generic;
using System.Data; using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows; using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace NPOI_Project namespace ExcelExport.UI
{ {
/// <summary> /// <summary>
/// Interaction logic for MainWindow.xaml /// Interaction logic for MainWindow.xaml
...@@ -22,7 +35,12 @@ namespace NPOI_Project ...@@ -22,7 +35,12 @@ namespace NPOI_Project
private void MainWindow_Loaded(object sender, RoutedEventArgs e) private void MainWindow_Loaded(object sender, RoutedEventArgs e)
{ {
_dataTable = XmlHelper.WriteToTable("国际数据主要国家(地区)年度数据.xml"); _dataTable = new XmlData().GetTableData("国际数据主要国家(地区)年度数据.xml");
if (_dataTable == null)
{
MessageBox.Show("加载数据失败!");
return;
}
this.Title = _dataTable.TableName; this.Title = _dataTable.TableName;
DataView dv = new DataView(_dataTable); DataView dv = new DataView(_dataTable);
this.dt.ItemsSource = dv; this.dt.ItemsSource = dv;
...@@ -35,10 +53,25 @@ namespace NPOI_Project ...@@ -35,10 +53,25 @@ namespace NPOI_Project
MessageBox.Show("没有找到要导出的数据"); MessageBox.Show("没有找到要导出的数据");
return; return;
} }
IExport export = null;
string exportType = this.combox.SelectionBoxItem.ToString();
switch (exportType)
{
case "NPOI":
export = new NPOIExport();
break;
case "EPPlus":
export = new EPPlusExport();
break;
}
if (export is null)
{
MessageBox.Show("没有找到要导出的方法");
return;
}
bool flag = export.Export(_dataTable, AppDomain.CurrentDomain.BaseDirectory + _dataTable.TableName + "_" + exportType + ".xlsx");
MessageBox.Show(flag ? "导出成功" : "导出失败");
string filepath = AppDomain.CurrentDomain.BaseDirectory + "111.xlsx";
bool falg = ExcelHelper.Export(_dataTable, filepath);
MessageBox.Show(falg ? "导出成功" : "导出失败");
} }
} }
} }

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 16
VisualStudioVersion = 16.0.31205.134
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ExcelExport.Base", "ExcelExport.Base\ExcelExport.Base.csproj", "{0A0A2C51-4EA3-4CD3-AC82-2235C1C5383C}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Excel.Export.Data", "Excel.Export.Data\Excel.Export.Data.csproj", "{D7DC9BB1-18A7-4556-BC57-4C48ECBA2789}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ExcelExport.Export", "ExcelExport.Export\ExcelExport.Export.csproj", "{0A1CEA3F-E06A-4C33-95F8-96920998E1C0}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ExcelExport.UI", "ExcelExport.UI\ExcelExport.UI.csproj", "{92A3D018-D76D-43D1-A94C-C9F2E8B41A00}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{0A0A2C51-4EA3-4CD3-AC82-2235C1C5383C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{0A0A2C51-4EA3-4CD3-AC82-2235C1C5383C}.Debug|Any CPU.Build.0 = Debug|Any CPU
{0A0A2C51-4EA3-4CD3-AC82-2235C1C5383C}.Release|Any CPU.ActiveCfg = Release|Any CPU
{0A0A2C51-4EA3-4CD3-AC82-2235C1C5383C}.Release|Any CPU.Build.0 = Release|Any CPU
{D7DC9BB1-18A7-4556-BC57-4C48ECBA2789}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{D7DC9BB1-18A7-4556-BC57-4C48ECBA2789}.Debug|Any CPU.Build.0 = Debug|Any CPU
{D7DC9BB1-18A7-4556-BC57-4C48ECBA2789}.Release|Any CPU.ActiveCfg = Release|Any CPU
{D7DC9BB1-18A7-4556-BC57-4C48ECBA2789}.Release|Any CPU.Build.0 = Release|Any CPU
{0A1CEA3F-E06A-4C33-95F8-96920998E1C0}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{0A1CEA3F-E06A-4C33-95F8-96920998E1C0}.Debug|Any CPU.Build.0 = Debug|Any CPU
{0A1CEA3F-E06A-4C33-95F8-96920998E1C0}.Release|Any CPU.ActiveCfg = Release|Any CPU
{0A1CEA3F-E06A-4C33-95F8-96920998E1C0}.Release|Any CPU.Build.0 = Release|Any CPU
{92A3D018-D76D-43D1-A94C-C9F2E8B41A00}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{92A3D018-D76D-43D1-A94C-C9F2E8B41A00}.Debug|Any CPU.Build.0 = Debug|Any CPU
{92A3D018-D76D-43D1-A94C-C9F2E8B41A00}.Release|Any CPU.ActiveCfg = Release|Any CPU
{92A3D018-D76D-43D1-A94C-C9F2E8B41A00}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {90D67497-137C-4C47-A711-6054057D3993}
EndGlobalSection
EndGlobal
<Window x:Class="NPOI_Project.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"
xmlns:local="clr-namespace:NPOI_Project"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800" WindowStartupLocation="CenterScreen">
<DockPanel LastChildFill="True">
<Button Content="导出" x:Name="exportBtn" DockPanel.Dock="Top" Cursor="Hand" Width="150" Style="{StaticResource PrimaryButtonStyle1}" HorizontalAlignment="Right"/>
<DataGrid x:Name="dt" AutoGenerateColumns="True" HorizontalScrollBarVisibility="Visible" Width="780" />
</DockPanel>
</Window>

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 16
VisualStudioVersion = 16.0.31205.134
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "NPOI_Project", "NPOI_Project.csproj", "{B06D69F2-056A-435C-A37F-32FD6C1F0D2E}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{B06D69F2-056A-435C-A37F-32FD6C1F0D2E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{B06D69F2-056A-435C-A37F-32FD6C1F0D2E}.Debug|Any CPU.Build.0 = Debug|Any CPU
{B06D69F2-056A-435C-A37F-32FD6C1F0D2E}.Release|Any CPU.ActiveCfg = Release|Any CPU
{B06D69F2-056A-435C-A37F-32FD6C1F0D2E}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {90BBA2BF-EA0B-473E-8550-173F6E2A0374}
EndGlobalSection
EndGlobal
# ExcelExport
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册