Closedxml excel to pdf

Does ClosedXML have any function that can be used to save an excel file as PDF?

Currently i am using ClosedXML to create and populate the excel file and then using Interop to save as PDF.
But since Interop depends on the MS Office installed on the syatem the formatting changes on every version of MS Office. And since ClosedXML doesnt require having MS office installed it would be nice to be able to export or save as PDF directly from it without using Interops.

asked Mar 24, 2017 at 13:04

ilmenite's user avatar

2

Does ClosedXML have any function that can be used to save an excel file as PDF?

No.

answered Mar 25, 2017 at 11:27

Francois Botha's user avatar

Francois BothaFrancois Botha

4,3491 gold badge33 silver badges43 bronze badges

2

Instead you can use the free version of GemBox.Spreadsheet.

Also look at the top 10 libraries which allows us to manipulate excel.

However GemBox was the only free and featured one that I found with the purpose of creating an invoice report for a website, by converting excel to pdf.

answered Sep 14, 2021 at 9:47

Sujoy's user avatar

SujoySujoy

92510 silver badges25 bronze badges

Содержание

  1. ClosedXML
  2. Install ClosedXML via NuGet
  3. What can you do with this?
  4. Frequent answers
  5. Extensions
  6. Developer guidelines
  7. Быстрый старт
  8. Установка ClosedXML.Report через NuGet
  9. Особенности
  10. Как использовать?
  11. ClosedXML/ClosedXML
  12. Sign In Required
  13. Launching GitHub Desktop
  14. Launching GitHub Desktop
  15. Launching Xcode
  16. Launching Visual Studio Code
  17. Latest commit
  18. Git stats
  19. Files
  20. README.md
  21. About
  22. ClosedXML
  23. Install ClosedXML via NuGet
  24. What can you do with this?
  25. Frequent answers
  26. Extensions
  27. Developer guidelines
  28. 【.NET Core】【ClosedXML】Copy Excel worksheets
  29. Intro
  30. Environments
  31. Original worksheet
  32. Copy worksheets
  33. SpreadsheetLoader.cs
  34. Result
  35. Copied
  36. Not copied
  37. Copy manually
  38. Cell(Range) names
  39. SpreadsheetLoader.cs
  40. Height, Width
  41. Pictures
  42. Get execptions?
  43. Result
  44. Shapes(Include graphs)
  45. Theme colors
  46. Result
  47. Top comments (4)
  48. An Animated Guide to Node.js Event Loop
  49. Read next
  50. #Rust 🦀 – Working with hashmaps is cool. And a little C# experience 😄
  51. Better Runtime Diagnostics
  52. Trigger an automation pipeline after a Dev pipeline runs
  53. Regex for lazy developers
  54. More from Masui Masanori
  55. Join DEV and get the content you need
  56. Start your journey today.

ClosedXML

ClosedXML is a .NET library for reading, manipulating and writing Excel 2007+ (.xlsx, .xlsm) files. It aims to provide an intuitive and user-friendly interface to dealing with the underlying OpenXML API.

Install ClosedXML via NuGet

If you want to include ClosedXML in your project, you can install it directly from NuGet

To install ClosedXML, run the following command in the Package Manager Console

What can you do with this?

ClosedXML allows you to create Excel files without the Excel application. The typical example is creating Excel reports on a web server.

Example:

Frequent answers

  • ClosedXML is not thread-safe. There is no guarantee that parallel operations will work. The underlying OpenXML library is also not thread-safe.
  • If you get an exception The type initializer for ‘Gdip’ threw an exception. on Linux, try thesesolutions.

Extensions

Be sure to check out our ClosedXML extension projects

  • https://github.com/ClosedXML/ClosedXML.Report
  • https://github.com/ClosedXML/ClosedXML.Extensions.AspNet
  • https://github.com/ClosedXML/ClosedXML.Extensions.Mvc
  • https://github.com/ClosedXML/ClosedXML.Extensions.WebApi

Developer guidelines

The OpenXML specification is a large and complicated beast. In order for ClosedXML, the wrapper around OpenXML, to support all the features, we rely on community contributions. Before opening an issue to request a new feature, we’d like to urge you to try to implement it yourself and log a pull request.

Источник

Быстрый старт

ClosedXML.Report — это инструмент для создания отчетов и анализа данных в приложениях .NET с использованием Microsoft Excel. Это .NET-библиотека для создания отчетов Microsoft Excel, не требующая установки Excel на машине, на которой выполняется код. С помощью ClosedXML.Report вы можете легко экспортировать любые данные из ваших классов .NET в Excel с помощью XLSX-шаблона.

Установка ClosedXML.Report через NuGet

Если вы хотите включить ClosedXML.Report в свой проект, вы можете установить его непосредственно из NuGet

Чтобы установить ClosedXML.Report, запустите следующую команду в консоли диспетчера пакетов

или если у вас подписанная сборка то:

Особенности

  • Копирование форматирования ячеек
  • Копирование условного форматирования
  • Вертикальные и горизонтальные таблицы
  • Возможность применения формул Excel
  • Использование динамически рассчитываемых формул с синтаксисом C# и Linq
  • Операции с табличными данными: сортировка, группировка, общие функции.
  • Сводные таблицы
  • Контроль за построением отчёта с помощью управляющих тэгов
  • Вложенные области (master-detail)

Как использовать?

Чтобы создать отчет, вы должны сначала создать шаблон отчета. Вы можете применить любое форматирование к ячейкам рабочей книги, вставить изображения и изменить любой из параметров самой книги. В этом примере мы отключили отображение нулевых значений и спрятали линии сетки. ClosedXML.Report сохранит все изменения в шаблоне.

Template

Code

Result

Для получения дополнительной информации см. Документация и Тесты

Источник

ClosedXML/ClosedXML

Use Git or checkout with SVN using the web URL.

Work fast with our official CLI. Learn more.

Sign In Required

Please sign in to use Codespaces.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

README.md

ClosedXML is a .NET library for reading, manipulating and writing Excel 2007+ (.xlsx, .xlsm) files. It aims to provide an intuitive and user-friendly interface to dealing with the underlying OpenXML API.

For more information see the documentation or the wiki.

Release notes & migration guide

The public API is still not stable and it is a very good idea to read release notes and migration guide before each update.

  • If you get an exception Unable to find font font name or fallback font fallback font name. Install missing fonts or specify a different fallback font through ‘LoadOptions.DefaultGraphicEngine = new DefaultGraphicEngine(“Fallback font name”)’ , see help page about missing fonts.
  • ClosedXML is not thread-safe. There is no guarantee that parallel operations will work. The underlying OpenXML library is also not thread-safe.
  • If you get an exception The type initializer for ‘Gdip’ threw an exception. on Linux, you have to upgrade to 0.97+.

Install ClosedXML via NuGet

If you want to include ClosedXML in your project, you can install it directly from NuGet

To install ClosedXML, run the following command in the Package Manager Console

What can you do with this?

ClosedXML allows you to create Excel files without the Excel application. The typical example is creating Excel reports on a web server.

Example:

Be sure to check out our ClosedXML extension projects

The OpenXML specification is a large and complicated beast. In order for ClosedXML, the wrapper around OpenXML, to support all the features, we rely on community contributions. Before opening an issue to request a new feature, we’d like to urge you to try to implement it yourself and log a pull request.

  • Project originally created by Manuel de Leon
  • Current maintainer: Jan Havlíček
  • Former maintainer and lead developer: Francois Botha
  • Master of Computing Patterns: Aleksei Pankratev
  • Logo design by @Tobaloidee

About

ClosedXML is a .NET library for reading, manipulating and writing Excel 2007+ (.xlsx, .xlsm) files. It aims to provide an intuitive and user-friendly interface to dealing with the underlying OpenXML API.

Источник

ClosedXML

ClosedXML is a .NET library for reading, manipulating and writing Excel 2007+ (.xlsx, .xlsm) files. It aims to provide an intuitive and user-friendly interface to dealing with the underlying OpenXML API.

Install ClosedXML via NuGet

If you want to include ClosedXML in your project, you can install it directly from NuGet

To install ClosedXML, run the following command in the Package Manager Console

What can you do with this?

ClosedXML allows you to create Excel files without the Excel application. The typical example is creating Excel reports on a web server.

Example:

Frequent answers

  • ClosedXML is not thread-safe. There is no guarantee that parallel operations will work. The underlying OpenXML library is also not thread-safe.
  • If you get an exception The type initializer for ‘Gdip’ threw an exception. on Linux, try thesesolutions.

Extensions

Be sure to check out our ClosedXML extension projects

  • https://github.com/ClosedXML/ClosedXML.Report
  • https://github.com/ClosedXML/ClosedXML.Extensions.AspNet
  • https://github.com/ClosedXML/ClosedXML.Extensions.Mvc
  • https://github.com/ClosedXML/ClosedXML.Extensions.WebApi

Developer guidelines

The OpenXML specification is a large and complicated beast. In order for ClosedXML, the wrapper around OpenXML, to support all the features, we rely on community contributions. Before opening an issue to request a new feature, we’d like to urge you to try to implement it yourself and log a pull request.

Источник

【.NET Core】【ClosedXML】Copy Excel worksheets

Intro

This time, I will try copying Microsoft Excel worksheets from one workbook to another workbook by ClosedXML.

Environments

  • .NET ver.5.0.103
  • ClosedXML ver.0.95.4

Original worksheet

Copy worksheets

(Edit on 2021-02-23)

IXLWorksheet of ClosedXML only has a «CopyTo» method what copies from one worksheet to a new worksheet in same workbook.

I can copy worksheet like below.

Exit fullscreen mode

It can copy them.

  • Cell values
  • Formulas
  • Colors
  • Borders
  • Merged cell
  • Pictures
  • Cell(Range name)

Thank you very much, @igitur 🙂

To copy to another book, I can convert the worksheet to Range and copy to another worksheet.

SpreadsheetLoader.cs

Exit fullscreen mode

Result

Copied

  • Cell values
  • Formulas
  • Colors
  • Borders
  • Merged cell

Not copied

  • Cell(Range) names
  • Height, Width
  • Pictures
  • Shapes(Include graphs)

and Theme colors

Copy manually

Cell(Range) names

To copy cell(range) names, I have to get their ranges.

SpreadsheetLoader.cs

Exit fullscreen mode

Height, Width

Exit fullscreen mode

Pictures

Exit fullscreen mode

Get execptions?

I couldn’t copy some pictures.
When I created an Excel workbook by using Excel templates, I got an exception like below.

Exit fullscreen mode

I checked the picture format.

Exit fullscreen mode

Its format was «bmp».

So I add another bmp format picture and remove the first one.
But I didn’t get the exception.

I don’t know what the differences between the them :(.

Result

Shapes(Include graphs)

ClosedXML doesn’t have copying shapes functions.

Because EPPlus, OpenXML, etc. have the functions, when I need copy shapes, I may need choose other libraries.

Theme colors

I checked the ThemeColor like below.

Exit fullscreen mode

Result

Exit fullscreen mode

I thought the reason why the colors changed was defined colors hadn’t been same as Excel.
So I try searching the way to get color by another format for example color codes.

There is a IXLWorksheet.CopyTo(XLWorkbook workbook, String newSheetName) method to copy a worksheet directly to another workbook.

Thank you for your information.
I missed that method 🙂

For the exception when copying a picture, please log a new issue at github.com/ClosedXML/ClosedXML and be sure to fill in the issue template well, including code sample and test file.

Thank you so much.
I added a new issue at ClosedXML repository 🙂
github.com/ClosedXML/ClosedXML/iss.

For further actions, you may consider blocking this person and/or reporting abuse

An Animated Guide to Node.js Event Loop

Read next

#Rust 🦀 – Working with hashmaps is cool. And a little C# experience 😄

El Bruno — Jan 25

Better Runtime Diagnostics

Arcueid — Jan 24

Trigger an automation pipeline after a Dev pipeline runs

tswiftma — Dec 21 ’22

Regex for lazy developers

Ilya Ermoshin — Jan 4

More from Masui Masanori

Join DEV and get the content you need

Stay up-to-date on the latest developer content to stay ahead of the curve.

Start your journey today.

Once suspended, masanori_msl will not be able to comment or publish posts until their suspension is removed.

Once unsuspended, masanori_msl will be able to comment and publish posts again.

Once unpublished, all posts by masanori_msl will become hidden and only accessible to themselves.

If masanori_msl is not suspended, they can still re-publish their posts from their dashboard.

Once unpublished, this post will become invisible to the public and only accessible to Masui Masanori.

They can still re-publish the post if they are not suspended.

Thanks for keeping DEV Community safe. Here is what you can do to flag masanori_msl:

masanori_msl consistently posts content that violates DEV Community’s code of conduct because it is harassing, offensive or spammy.

Unflagging masanori_msl will restore default visibility to their posts.

DEV Community — A constructive and inclusive social network for software developers. With you every step of your journey.

Built on Forem — the open source software that powers DEV and other inclusive communities.

Made with love and Ruby on Rails. DEV Community © 2016 — 2023.

We’re a place where coders share, stay up-to-date and grow their careers.

Источник

Быстрый старт

ClosedXML.Report — это инструмент для создания отчетов и анализа данных в приложениях .NET с использованием Microsoft Excel. Это .NET-библиотека для создания отчетов Microsoft Excel, не требующая установки Excel на машине, на которой выполняется код. С помощью ClosedXML.Report вы можете легко экспортировать любые данные из ваших классов .NET в Excel с помощью XLSX-шаблона.

Установка ClosedXML.Report через NuGet

Если вы хотите включить ClosedXML.Report в свой проект, вы можете установить его непосредственно из NuGet

Чтобы установить ClosedXML.Report, запустите следующую команду в консоли диспетчера пакетов

PM> Install-Package ClosedXML.Report

или если у вас подписанная сборка то:

PM> Install-Package ClosedXML.Report.Signed

Особенности

  • Копирование форматирования ячеек
  • Копирование условного форматирования
  • Вертикальные и горизонтальные таблицы
  • Возможность применения формул Excel
  • Использование динамически рассчитываемых формул с синтаксисом C# и Linq
  • Операции с табличными данными: сортировка, группировка, общие функции.
  • Сводные таблицы
  • Контроль за построением отчёта с помощью управляющих тэгов
  • Вложенные области (master-detail)

Как использовать?

Чтобы создать отчет, вы должны сначала создать шаблон отчета. Вы можете применить любое форматирование к ячейкам рабочей книги, вставить изображения и изменить любой из параметров самой книги. В этом примере мы отключили отображение нулевых значений и спрятали линии сетки. ClosedXML.Report сохранит все изменения в шаблоне.

Template

template1

Code

    protected void Report()
    {
        const string outputFile = @".Outputreport.xlsx";
        var template = new XLTemplate(@".Templatesreport.xlsx");

        using (var db = new DbDemos())
        {
            var cust = db.customers.LoadWith(c => c.Orders).First();
            template.AddVariable(cust);
            template.Generate();
        }

        template.SaveAs(outputFile);

        //Show report
        Process.Start(new ProcessStartInfo(outputFile) { UseShellExecute = true });
    }

Result

result1

Для получения дополнительной информации см. Документация и Тесты

Masui Masanori

Intro

From the last result, I can print any contents what are drawn on a canvas.

  • 【.NET 5】【WPF】Edit and print PDF files 1

This time, I try drawing a spreadsheet on the canvas.

Environments

  • .NET ver.5.0.101
  • Microsoft.Extensions.DependencyInjection ver.5.0.1
  • ClosedXML ver.0.95.4

Get cell values from spreadsheets

First, I get cell informations by ClosedXML.

  • GitHub — ClosedXML/ClosedXML
  • 【.NET Core】【ClosedXML】Getting cell values 1
  • 【.NET Core】【ClosedXML】Getting cell values 2

Font.cs

using System.Drawing;
namespace PdfPrintSample.Spreadsheets.Values
{
    public record Font
    {
        public string Name { get; init; } = "Meiryo UI";
        public double Size { get; init; } = 12d;
        public Color Color { get; init; } = Color.Black;
        public bool Bold { get; init; }
        public bool Italic { get; init; }
        public string Underline { get; init; } = "";

    }
}

Enter fullscreen mode

Exit fullscreen mode

Border.cs

using System.Drawing;
namespace PdfPrintSample.Spreadsheets.Values
{
    public record Border
    {
        public string Style { get; init; } = "None";
        public Color Color { get; init; } = Color.Black;
    }
}

Enter fullscreen mode

Exit fullscreen mode

Borders.cs

namespace PdfPrintSample.Spreadsheets.Values
{
    public record Borders
    {
        public Border Left { get; init; } = new Border();
        public Border Top { get; init; } = new Border();
        public Border Right { get; init; } = new Border();
        public Border Bottom { get; init; } = new Border();
        // /
        public Border DiagonalUp { get; init; } = new Border();
        // 
        public Border DiagonalDown { get; init; } = new Border();
    }
}

Enter fullscreen mode

Exit fullscreen mode

MergedRange.cs

namespace PdfPrintSample.Spreadsheets.Values
{
    public record MergedRange
    {
        public int ColumnFrom { get; init; }
        public int RowFrom { get; init; }
        public int ColumnTo { get; init; }
        public int RowTo { get; init; }
    }
}

Enter fullscreen mode

Exit fullscreen mode

Cell.cs

using System.Drawing;
namespace PdfPrintSample.Spreadsheets.Values
{
    public record Cell
    {
        public int Row { get; init; }
        public int Column { get; init; }
        public double Height { get; init; }
        public double Width { get; init; }
        public string Text { get; init; } = "";
        public Color BackgroundColor { get; init; }
        public Font Font { get; init; } = new Font();
        public Borders Borders { get; init; } = new Borders();
        public MergedRange? MergedRange { get; init; }
    }
}

Enter fullscreen mode

Exit fullscreen mode

Worksheet.cs

using System.Collections.Generic;
namespace PdfPrintSample.Spreadsheets.Values
{
    public class Worksheet
    {
        public string Name { get; init; } = "";
        public List<Cell> Cells { get; init; } = new List<Cell>();
    }
}

Enter fullscreen mode

Exit fullscreen mode

Get from a spreadsheet

ISpreadsheetLoader.cs

using PdfPrintSample.Spreadsheets.Values;
namespace PdfPrintSample.Spreadsheets
{
    public interface ISpreadsheetLoader
    {
        Worksheet? Load(string filePath, string sheetName);
    }
}

Enter fullscreen mode

Exit fullscreen mode

SpreadsheetLoader.cs

using System.Drawing;
using System;
using System.IO;
using ClosedXML.Excel;
using NLog;
using PdfPrintSample.Spreadsheets.Values;

namespace PdfPrintSample.Spreadsheets
{
    public class SpreadsheetLoader: ISpreadsheetLoader
    {
        private readonly Logger logger = LogManager.GetCurrentClassLogger();
        public Worksheet? Load(string filePath, string sheetName)
        {
            if(File.Exists(filePath) == false)
            {
                logger.Error("File was not found");
                return null;
            }
            try
            {
                using(var book = new XLWorkbook(filePath))
                {
                    var sheet = book.Worksheet(sheetName);

                    var result = new Values.Worksheet{
                        Name = sheetName,
                    };
                    for(var column = 1; column <= 6; column++)
                    {
                        for(var row = 1; row <= 6; row++)
                        {
                            result.Cells.Add(GetCell(sheet, column, row));
                        }
                    }
                    return result;
                }
            }
            catch(Exception ex)
            {
                logger.Error(ex.Message);
                return null;
            }
        }
        public Values.Cell GetCell(IXLWorksheet sheet, int column, int row)
        {
            var cell = sheet.Cell(row, column);

            return new Values.Cell
            {
                Row = row,
                Column = column,
                Height = sheet.Row(row).Height,
                Width = sheet.Column(column).Width,
                Text = cell.GetString(),
                BackgroundColor = cell.Style.Fill.BackgroundColor.Color,
                Font = GetFont(cell),
                Borders = GetBorders(cell),
                MergedRange = GetMergedRange(cell),
            };
        }
        public Values.Borders GetBorders(IXLCell cell)
        {
            var border = cell.Style.Border;
            var diagonalBorder = new Border
            {
                Style = border.DiagonalBorder.ToString(),
                Color = GetColor(border.DiagonalBorderColor),
            };

            return new Values.Borders
            {
                Left = new Border {
                    Style = border.LeftBorder.ToString(),
                    Color = GetColor(border.LeftBorderColor),
                },
                Top = new Border 
                {
                    Style = border.TopBorder.ToString(),
                    Color = GetColor(border.TopBorderColor),
                },
                Right = new Border 
                {
                    Style = border.RightBorder.ToString(),
                    Color = GetColor(border.RightBorderColor),
                },
                Bottom = new Border 
                {
                    Style = border.TopBorder.ToString(),
                    Color = GetColor(border.TopBorderColor),
                },
                DiagonalUp = (border.DiagonalUp)? diagonalBorder: new Border(),
                DiagonalDown = (border.DiagonalDown)? diagonalBorder: new Border(),
            };
        }
        public Values.Font GetFont(IXLCell cell)
        {
            return new Values.Font
            {
                Name = cell.Style.Font.FontName,
                Size = cell.Style.Font.FontSize,
                Color = GetColor(cell.Style.Font.FontColor),
                Bold = cell.Style.Font.Bold,
                Italic = cell.Style.Font.Italic,
                Underline = cell.Style.Font.Underline.ToString(),
            };
        }
        public Values.MergedRange? GetMergedRange(IXLCell cell)
        {
            var mergedRange = cell.MergedRange();
            if(mergedRange == null)
            {
                return null;
            }
            var cellFrom = mergedRange.FirstCell();
            var cellTo = mergedRange.LastCell();
            return new Values.MergedRange
            {
                ColumnFrom = cellFrom.Address.ColumnNumber,
                RowFrom = cellFrom.Address.RowNumber,
                ColumnTo = cellTo.Address.ColumnNumber,
                RowTo = cellTo.Address.RowNumber,
            };
        }
        public Color GetColor(XLColor color)
        {
            if(color.ColorType == XLColorType.Color)
            {
                return color.Color;
            }
            return Color.Black;
        }
    }
}

Enter fullscreen mode

Exit fullscreen mode

Getting Font Colors & Border Colors

Fonts and Borders have two color types.

When their color types are «Color», I can get color from «XLColor.Color».
But if they are «Theme», I must use «XLColor.ThemeColor» or I will get an error.

DI

Last time, I read PDF and print it in the MainWindow’s code behind.
But now, ther are many functions in the project, so I try separating them from the code behind.

First, I add DI container.

Using DI in WPF app is pretty much the same as with the Console app.

  • 【.NET Core】Play with Console App

Because WPF doesn’t have a «program.cs» and a main method, I need adding using DI codes in App.xaml and its code behind.

App.xaml

<Application x:Class="PdfPrintSample.App"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:local="clr-namespace:PdfPrintSample"
             Startup="Start">
    <Application.Resources>
    </Application.Resources>
</Application>

Enter fullscreen mode

Exit fullscreen mode

App.xaml.cs

using System;
using System.Windows;
using Microsoft.Extensions.DependencyInjection;
using PdfPrintSample.Main;
using PdfPrintSample.Spreadsheets;

namespace PdfPrintSample
{
    public partial class App : Application
    {
        public void Start(object sender, StartupEventArgs e)
        {
            var servicesProvider = BuildDi();
            using (servicesProvider as IDisposable)
            {
                var main = servicesProvider.GetRequiredService<MainWindow>();
                main.Show();
            }
        }
        private static IServiceProvider BuildDi()
        {
            var services = new ServiceCollection();
            services.AddScoped<MainWindow>();
            services.AddScoped<MainViewModel>();
            services.AddScoped<ISpreadsheetLoader, SpreadsheetLoader>();
            return services.BuildServiceProvider();
        }
    }
}

Enter fullscreen mode

Exit fullscreen mode

MainWindow.xaml.cs

...
namespace PdfPrintSample.Main
{
    public partial class MainWindow : Window
    {
        private readonly Logger logger = LogManager.GetCurrentClassLogger();
        private readonly ISpreadsheetLoader spreadsheets;
        public MainWindow(ISpreadsheetLoader spreadsheets)
        {
            this.spreadsheets = spreadsheets;
            InitializeComponent();
        }
...

Enter fullscreen mode

Exit fullscreen mode

  • Application.Startup Event (System.Windows) | Microsoft Docs

ClosedXML

Release NuGet Badge .NET Framework .NET Standard Build status
Open Source Helpers

💾 Download unstable CI build

ClosedXML is a .NET library for reading, manipulating and writing Excel 2007+ (.xlsx, .xlsm) files. It aims to provide an intuitive and user-friendly interface to dealing with the underlying OpenXML API.

For more information see the documentation or the wiki.

Release notes & migration guide

The public API is still not stable and it is a very good idea to read release notes and migration guide before each update.

  • Release notes for 0.100
  • Migration guide for 0.100
  • Release notes for 0.97

Frequent answers

  • If you get an exception Unable to find font font name or fallback font fallback font name. Install missing fonts or specify a different fallback font through ‘LoadOptions.DefaultGraphicEngine = new DefaultGraphicEngine(“Fallback font name”)’, see help page about missing fonts.
  • ClosedXML is not thread-safe. There is no guarantee that parallel operations will work. The underlying OpenXML library is also not thread-safe.
  • If you get an exception The type initializer for 'Gdip' threw an exception. on Linux, you have to upgrade to 0.97+.

Install ClosedXML via NuGet

If you want to include ClosedXML in your project, you can install it directly from NuGet

To install ClosedXML, run the following command in the Package Manager Console

PM> Install-Package ClosedXML

What can you do with this?

ClosedXML allows you to create Excel files without the Excel application. The typical example is creating Excel reports on a web server.

Example:

using (var workbook = new XLWorkbook())
{
    var worksheet = workbook.Worksheets.Add("Sample Sheet");
    worksheet.Cell("A1").Value = "Hello World!";
    worksheet.Cell("A2").FormulaA1 = "=MID(A1, 7, 5)";
    workbook.SaveAs("HelloWorld.xlsx");
}

Extensions

Be sure to check out our ClosedXML extension projects

  • https://github.com/ClosedXML/ClosedXML.Report
  • https://github.com/ClosedXML/ClosedXML.Extensions.AspNet
  • https://github.com/ClosedXML/ClosedXML.Extensions.Mvc
  • https://github.com/ClosedXML/ClosedXML.Extensions.WebApi

Developer guidelines

The OpenXML specification is a large and complicated beast. In order for ClosedXML, the wrapper around OpenXML, to support all the features, we rely on community contributions. Before opening an issue to request a new feature, we’d like to urge you to try to implement it yourself and log a pull request.

Please read the full developer guidelines.

Credits

  • Project originally created by Manuel de Leon
  • Current maintainer: Jan Havlíček
  • Former maintainer and lead developer: Francois Botha
  • Master of Computing Patterns: Aleksei Pankratev
  • Logo design by @Tobaloidee

0 / 0 / 0

Регистрация: 10.10.2018

Сообщений: 12

1

02.12.2021, 10:26. Показов 2445. Ответов 16


Студворк — интернет-сервис помощи студентам

Всем привет.
Столкнулся с такой задачкой.
Я в программе собираю некий отчет с помощью ClosedXML.
На выходе у меня получается xlsx файл.
Далее мне нужно его конвертировать в PDF.
И вот тут проблема. Не могу найти решения.

Какие есть способы конвертирования из xlsx в pdf?

Главное условие: у пользователя может не быть установленного пакета офиса.
т.е. Microsoft.Office.Interop.Excel не подойдет.



0



Эксперт .NET

11443 / 7770 / 1190

Регистрация: 21.01.2016

Сообщений: 29,152

02.12.2021, 10:53

2

MeeLStorM, так может сразу формировать PDF, если в итоге именно он и нужен? Для работы с PDF тоже библиотеки есть.



1



bite

3693 / 3126 / 692

Регистрация: 13.04.2015

Сообщений: 7,314

02.12.2021, 10:55

3

Цитата
Сообщение от MeeLStorM
Посмотреть сообщение

Какие есть способы конвертирования из xlsx в pdf?

Напрямую сконвертировать вы вряд ли найдете удовлетворяющее вас решение.
Лучше использовать две библиотеки — одну для чтения из xlsx другую для создания PDF

Добавлено через 1 минуту

Цитата
Сообщение от Usaga
Посмотреть сообщение

может сразу формировать PDF

Действительно.



0



0 / 0 / 0

Регистрация: 10.10.2018

Сообщений: 12

02.12.2021, 11:41

 [ТС]

4

Цитата
Сообщение от Usaga
Посмотреть сообщение

MeeLStorM, так может сразу формировать PDF, если в итоге именно он и нужен? Для работы с PDF тоже библиотеки есть.

Просто xlsx тоже нужен))
И там удобно графики строить красивые.
Через PDF подобного не делал.



0



Эксперт .NET

11443 / 7770 / 1190

Регистрация: 21.01.2016

Сообщений: 29,152

02.12.2021, 11:43

5

MeeLStorM, тогда как выше посоветовали: два отчёта.

Ещё один возможный путь — взять средства построения отчётов (Microsoft Report Viewer, Crystal Reports, Fast Reports, etc). Эти имеют свои средства для формирования шаблона отчёта (что минус больше), но так же имеют возможность экспортировать полученный отчёт в разные форматы.



1



798 / 581 / 207

Регистрация: 21.02.2019

Сообщений: 2,095

02.12.2021, 12:05

6

MeeLStorM,
.. гуголь говорит нам, что есть вот такое
GemBox.Spreadsheet
… и оно позволяет экспортировать xlsx в pdf, но в бесплатной версии есть ограничения … сам я не пробовал …



1



Модератор

Эксперт .NET

13628 / 9862 / 2636

Регистрация: 21.04.2018

Сообщений: 29,369

Записей в блоге: 2

02.12.2021, 16:00

7

Цитата
Сообщение от MeeLStorM
Посмотреть сообщение

нужно его конвертировать в PDF.
И вот тут проблема. Не могу найти решения.

Сразу могу сказать нормального бесплатного инструмента не найдёте.
Всё, что работает с Офиcом и PDF либо платно, либо имеет какие-то ограничения, либо работает криво (особенно для сложного форматирования).
Если есть в системе pdf-принтер, то можно попробовать на него вывести.



1



0 / 0 / 0

Регистрация: 10.10.2018

Сообщений: 12

02.12.2021, 16:14

 [ТС]

8

Цитата
Сообщение от carrotik
Посмотреть сообщение

MeeLStorM,
.. гуголь говорит нам, что есть вот такое
GemBox.Spreadsheet
… и оно позволяет экспортировать xlsx в pdf, но в бесплатной версии есть ограничения … сам я не пробовал …

Вот как раз его смотрю. Работает довольно адекватно. Ограничение бесплатной версии 150 строк, 5 страниц.



0



1494 / 888 / 324

Регистрация: 17.05.2015

Сообщений: 3,372

02.12.2021, 22:15

9



1



1100 / 826 / 258

Регистрация: 30.04.2009

Сообщений: 3,426

02.12.2021, 22:36

10

Цитата
Сообщение от Рядовой
Посмотреть сообщение

используйте spire pdf

«Free version is limited to 10 pages of PDF» (c)



0



Эксперт .NET

11443 / 7770 / 1190

Регистрация: 21.01.2016

Сообщений: 29,152

03.12.2021, 06:02

11

Цитата
Сообщение от nicolas2008
Посмотреть сообщение

«Free version is limited to 10 pages of PDF» (c)

Если ТС не для себя пишет, то контора может и купить. Это может оказаться дешевле и быстрее, чем ждать пока ТС это напишет сам или найдёт иное решение.



0



1494 / 888 / 324

Регистрация: 17.05.2015

Сообщений: 3,372

03.12.2021, 08:32

12

nicolas2008, я же скинул ссылку на бесплатную версию



0



0 / 0 / 0

Регистрация: 10.10.2018

Сообщений: 12

15.12.2021, 12:06

 [ТС]

13

В итоге использовал GemBox.Spreadsheet + PdfSharp
Так как GemBox имеет ограничение в 150 строк и 5 листов, делаю несколько pdf файлов, потом склеиваю их с помощью PdfSharp.

spire pdf не подошел, так как в бесплатной версии он добавляет всякий мусор в виде рекламы на последнем листе и водяных знаков на каждой странице.

Всем большое спасибо за советы!



0



bite

3693 / 3126 / 692

Регистрация: 13.04.2015

Сообщений: 7,314

15.12.2021, 12:11

14

Лучший ответ Сообщение было отмечено Рядовой как решение

Решение

Цитата
Сообщение от MeeLStorM
Посмотреть сообщение

GemBox.Spreadsheet + PdfSharp

Я использовал iTextSharp без всяких танцев с бубном.



0



0 / 0 / 0

Регистрация: 10.10.2018

Сообщений: 12

15.12.2021, 12:13

 [ТС]

15

Цитата
Сообщение от I can
Посмотреть сообщение

Я использовал iTextSharp без всяких танцев с бубном.

iTextSharp разве умеет конвертировать из xlsx в pdf?



0



798 / 581 / 207

Регистрация: 21.02.2019

Сообщений: 2,095

15.12.2021, 12:21

16

Цитата
Сообщение от I can
Посмотреть сообщение

Я использовал iTextSharp без всяких танцев с бубном.

..ну, скажем так, руками накодить отчет (да если с картинками) в iTextSharp — это не нажать пару кнопок, постучать по бубну тоже надо ..



0



bite

3693 / 3126 / 692

Регистрация: 13.04.2015

Сообщений: 7,314

15.12.2021, 12:39

17

Цитата
Сообщение от carrotik
Посмотреть сообщение

постучать по бубну тоже надо

Так, слегка

Добавлено через 2 минуты

Цитата
Сообщение от MeeLStorM
Посмотреть сообщение

iTextSharp разве умеет конвертировать из xlsx в pdf?

Опять двадцать пять… Ну если у вас все данные на руках, то нафига конвертировать, если можно создать сразу и xlsx и pdf ?



1



IT_Exp

Эксперт

87844 / 49110 / 22898

Регистрация: 17.06.2006

Сообщений: 92,604

15.12.2021, 12:39

Помогаю со студенческими работами здесь

Конвертация aspx в pdf
Привет! Подскажите пожалуйста как конвертировать в C# коде страницу .aspx в pdf

Конвертация потока c файлом XLS в поток c файлом XLSX
На сервер приходит поток Stream в котором содержится XLS файл. Для работы с Excel используется…

Бесплатные либы для создания, редактирования PDF, DOCX, XLSX, XLS, DOC и конвертации их между собой
Существует ли бесплатная библиотека, которая позволяет делать все и сразу — создавать,…

Конвертация всех pdf файлов из каталога
роясь на просторах интернета, нашел библиотеку для конвертирования pdf в графические изображения(в…

Конвертация Doc в PDF без использования Com.Interop
нужно конвертировать обычный вордовский файл в PDF. вопрос заключается в следующем,знает ли кто…

Пакетная конвертация PDF в DOC и печать любых документов на PDF-принтере
В первую очередь извините, если создал тему в неположенном разделе, но к сожалению найти близкий по…

Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:

17

If you have Excel spreadsheets generated from .NET Core applications, you may find it helpful to store your files in a PDF format.

Why do I need to convert an Excel spreadsheet to PDF?

Several reasons include:

  • Storing Excel spreadsheets for long-term preservation.
  • Not having MS Office installed on a system, but still wanting to open, print, or distribute your Excel spreadsheets.
  • Consistency of presentation of Excel spreadsheets when opened on different systems.

Alternatively, you may need to create and distribute the following company reports:

  • Profit & Loss Statement
  • Company Budget
  • Sales Forecast
  • Income Statement

GrapeCity Documents for Excel (GcExcel) is a high-speed, small-footprint spreadsheet API that requires no dependencies on Excel. With full .NET Core support, you can generate, load, modify, and convert spreadsheets in .NET Framework, .NET Core, Mono, and Xamarin. Apps using this spreadsheet API can be deployed to the cloud, Windows, Mac, or Linux.

Exporting Excel Spreadsheets to PDF in .NET

This demo will cover the following:

  • How to create an Excel Spreadsheet and save it to PDF
  • How to load an Excel Spreadsheet and save it to PDF

Note: When working with GcExcel on MAC or Linux, specify the Workbook.FontFolderPath and place the necessary fonts in it before exporting spreadsheets to PDF.

For more information, visit: Configure Fonts and Set Style.

Step 1: Create an Excel Spreadsheet

Follow this link to create a basic Excel spreadsheet on Windows, MAC, or Linux.

At the end of this tutorial, the spreadsheet will look like this:

convert

Step 2: Convert Excel Spreadsheets to PDF

In Step 1, we created an Excel spreadsheet using the GcExcel workbook and saved it to an Excel file. Instead of saving to Excel, you can directly save the workbook to PDF. Please note if you need to print the worksheet on a single PDF, you can set additional options through the PageSetup class of the worksheet.

worksheet.PageSetup.Orientation = PageOrientation.Landscape;  
worksheet.PageSetup.IsPercentScale = false;  
worksheet.PageSetup.FitToPagesWide = 1;  
worksheet.PageSetup.FitToPagesTall = 1;  
workbook.Save(@"SimpleBudget.pdf");

The PDF will look like this:

convert

Step 3: Load Excel spreadsheet and save to PDF

If you want to convert any of your Excel files (whether created with Excel, GcExcel, or from another third-party tool), you can do so in just three steps using GcExcel.

Suppose you want to convert an Excel file that calculates the total account data summary (per different age groups in a region) to a PDF.

convert

Follow these steps:

1. Create an empty workbook

var workbook = new GrapeCity.Documents.Excel.Workbook();

2. Load Excel file into the workbook

workbook.Open("AgingReport.xlsx");

3. Save To PDF

workbook.Save("AgingReport.pdf");

You have easily converted your excel spreadsheet to PDF:

convert

Supported PDF export features include:

  • Export Chart
  • Export Shape
  • PDF Export progress
  • Page Setup
  • PrintManager
  • Export text
  • Center across selection
  • Export outline column
  • Print transparent cell
  • Save background pictures to pdf
  • Export borders
  • Export Conditional Formatting
  • Export picture
  • Export Pivot Table
  • Export fills
  • Export sheet background image
  • Export slicers
  • Export sparklines
  • Export table
  • Save workbook to PDF
  • Save worksheet to PDF
  • Set document properties for PDF document
  • Set font’s folder
  • Set export image quality
  • Set PickTrayByPDFSize option for PDF document
  • Set security options for PDF document
  • Shrink to fit for wrapped text

Try the demo here.

Visit this help topic for more info on how to convert Excel to PDF in Java.

Please leave a comment below if this feature satisfies your requirement or you are looking for some additional features!

        public void Create(string filePath)
        {
            string tempFile = ExampleHelper.GetTempFilePath(filePath);
            try
            {
                new BasicTable().Create(tempFile);
                var workbook = new XLWorkbook(tempFile);
                var ws = workbook.Worksheet(1);

                // Get a range object
                var rngHeaders = ws.Range("B3:F3");

                // Insert some rows/columns before the range
                ws.Row(1).InsertRowsAbove(2);
                ws.Column(1).InsertColumnsBefore(2);

                // Change the background color of the headers
                rngHeaders.Style.Fill.BackgroundColor = XLColor.LightSalmon;

                ws.Columns().AdjustToContents();

                workbook.SaveAs(filePath);
            }
            finally
            {
                if (File.Exists(tempFile))
                {
                    File.Delete(tempFile);
                }
            }
        }
        /// Unpacks and writes out the FullNetwork file, returns the filepath 
        /// </summary>
        /// <param name="Network"></param>
        /// <param name="Path"></param>
        public string WriteOutExcelDocument(FullNetwork Network, string FileName)
        {
            // Build data table from the Network
            DataTable Table = new DataTable();
            Table.Columns.Add("Network ID");
            Table.Columns.Add("First Usable");
            Table.Columns.Add("Last Usable");
            Table.Columns.Add("Broadcast Address");

            foreach (var subnet in Network.Subnets)
            {
                // Add the data to each collumn
                DataRow Row = Table.NewRow();

                Row[0] = subnet.NetworkId;
                Row[1] = subnet.FirstUsable;
                Row[2] = subnet.LastUsable;
                Row[3] = subnet.BroadcastAddress;
                Table.Rows.Add(Row);
            }

            string FilePath = FileName + ".xlsx";

            XLWorkbook wb = new XLWorkbook();
            wb.Worksheets.Add(Table, "Subnet Data");
            wb.SaveAs(FilePath);

            return FilePath;
        }
        // Public
        public void Create(String filePath)
        {
            var workbook = new XLWorkbook();
            var ws = workbook.Worksheets.Add("Clearing Ranges");
            foreach (var ro in Enumerable.Range(1, 10))
            {
                foreach (var co in Enumerable.Range(1, 10))
                {
                    var cell = ws.Cell(ro, co);
                    cell.Value = cell.Address.ToString();
                    cell.Style.Alignment.Horizontal = XLAlignmentHorizontalValues.Center;
                    cell.Style.Fill.BackgroundColor = XLColor.Turquoise;
                    cell.Style.Font.Bold = true;
                }
            }

            // Clearing a range
            ws.Range("B1:C2").Clear();

            // Clearing a row in a range
            ws.Range("B4:C5").Row(1).Clear();

            // Clearing a column in a range
            ws.Range("E1:F4").Column(2).Clear();

            // Clear an entire row
            ws.Row(7).Clear();

            // Clear an entire column
            ws.Column("H").Clear();

            workbook.SaveAs(filePath);
        }
        private static void ExportToExcelFile(DataGridView dGV, string filename, string tabName)
        {
            //Creating DataTable
            DataTable dt = new DataTable();

            //Adding the Columns
            foreach (DataGridViewColumn column in dGV.Columns)
            {
                dt.Columns.Add(column.HeaderText, column.ValueType);
            }

            //Adding the Rows
            foreach (DataGridViewRow row in dGV.Rows)
            {
                dt.Rows.Add();
                foreach (DataGridViewCell cell in row.Cells)
                {
                    dt.Rows[dt.Rows.Count - 1][cell.ColumnIndex] = cell.Value.ToString();
                }
            }

            using (XLWorkbook wb = new XLWorkbook())
            {
                wb.Worksheets.Add(dt, tabName);
                wb.SaveAs(filename);
            }
        }  
        //----------------------------------------------------------------------
        // SubRoutine
        //----------------------------------------------------------------------
        private void editExcelSheet(string sheetName, TaskData td, TaskNoteData tnd, TaskIndData[] tid, PartnersData pd, TaskOp tod)
        {
            string tempFile = Folder.DefaultLocation() + @".~temp.xlsx";

            Cursor.Current = Cursors.WaitCursor;   // マウスカーソルを砂時計(Wait)

            using (oWBook = new XLWorkbook(FileName))
            {
                // シートを開く
                //oWSheet = oWBook.Worksheet(sheetName);
                oWSheet = oWBook.Worksheet(1);
                // 編集
                //MessageBox.Show("Excel書込み開始");
                editTaskDataPart(td);
                editTaskNoteDataPart(tnd);
                editTaskIndDataPart(tid);
                editPartnersDataPart(pd);
                editPersonsDataPart(tod);
                // 保存
                oWBook.SaveAs(tempFile);      // Excel保存
            }

            Cursor.Current = Cursors.Default;                        // マウスカーソルを戻す

            System.Diagnostics.Process.Start("Excel.exe", tempFile); // 表示用Excel

            //if (File.Exists(tempFile)) File.Delete(tempFile);
        }
        public void GenerateSalesPerCategoryResultFile(CategorySalesReport reportData, string fileName)
        {
            var wb = new XLWorkbook();
            var ws = wb.Worksheets.Add("Sales per Category");

            //Columns
            ws.Cell("B2").Value = "Category";
            ws.Cell("C2").Value = "Quantity";
            ws.Cell("D2").Value = "Amount Sold";

            var rowCount = 3;
            foreach (var row in reportData.Report)
            {
                var categoryCell = "B" + rowCount;
                var quantityCell = "C" + rowCount;
                var totalAmountCell = "D" + rowCount;

                ws.Cell(categoryCell).Value = row.Category;
                ws.Cell(quantityCell).Value = row.Quantity;
                ws.Cell(totalAmountCell).Value = row.TotalAmountSold;

                rowCount++;
            }

            var tableRange = ws.Range("B2", "D" + (rowCount - 1));
            var finBalanceTable = tableRange.CreateTable();
            finBalanceTable.Theme = XLTableTheme.TableStyleMedium16;

            ws.Columns().AdjustToContents();
            wb.SaveAs(ExcelSettings.Default.ExcelReportsDestinationFolder + fileName);
        }
        public void CreateExcelForPdf(string sheetName, PublishData pd, DataGridView dgv)
        {
            //string tempFile = Folder.DefaultLocation() + @".~temp.xlsx";
            string tempFile = "";

            Cursor.Current = Cursors.WaitCursor;   // マウスカーソルを砂時計(Wait)
            try
            {
                using (oWBook = new XLWorkbook(fileName))
                {
                    oWSheet = oWBook.Worksheet(sheetName);
                    switch (sheetName)
                    {
                    case "Volume":
                        tempFile = Folder.DefaultLocation() + @"" + pd.vTaskCode + ".xlsx";
                        editContractWorks(pd, dgv);
                        break;

                    default:
                        break;
                    }
                    oWBook.SaveAs(tempFile);        // Excel保存
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                Cursor.Current = Cursors.Default;   // マウスカーソルを戻す
                return;
            }
            Cursor.Current = Cursors.Default;       // マウスカーソルを戻す
        }
        public static void ExportExcels(DataTable data)
        {
            try
            {
                DataTable _myDataTable = data;

                _myDataTable.Columns[0].ColumnName = "#";
                _myDataTable.Columns[1].ColumnName = "შექმნის თარიღი";
                _myDataTable.Columns[2].ColumnName = "მოვლენის თარიღი";
                _myDataTable.Columns[3].ColumnName = "წერილის თარიღი";
                _myDataTable.Columns[4].ColumnName = "პროვაიდერი";
                _myDataTable.Columns[5].ColumnName = "ტიპი";
                _myDataTable.Columns[6].ColumnName = "საიდან";
                _myDataTable.Columns[7].ColumnName = "სად";
                _myDataTable.Columns[8].ColumnName = "ათვისებული თანხა";
                _myDataTable.Columns[9].ColumnName = "დასაბრუნებელი თანხა";
                _myDataTable.Columns[10].ColumnName = "მომხმარებელი";
                _myDataTable.Columns[11].ColumnName = "ინციდენტი";
                var workbook = new XLWorkbook();
                var sheet = workbook.Worksheets.Add(_myDataTable, "Letters");
                var table = sheet.Table(0);
                table.Theme = XLTableTheme.TableStyleMedium2;
                SaveFileDialog dialog = new SaveFileDialog();
                dialog.Filter = "Excel Files (*.xlsx)|*.xlsx";
                dialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
                dialog.FileName = "letters";
                if (dialog.ShowDialog() != DialogResult.OK) return;
                workbook.SaveAs(dialog.FileName);
                System.Diagnostics.Process.Start(dialog.FileName);
            }
            catch (Exception ex) { MessageBox.Show(ex.Message); }
        }
    protected void exportToExcel_Click(object sender, EventArgs e)
    {
        LinkButton btnOption = (LinkButton)sender;
        var        value     = btnOption.CommandArgument;
        var        Opt       = btnOption.CommandName;

        cmpObj.campaignId = value.ToString();
        cmpObj.option     = Opt.ToString();
        DataTable dtTemp = cmpObj.getCampaignReportDetailsByCampaignId(cmpObj);

        if (dtTemp.Rows.Count > 0)
        {
            dtTemp.Columns["VoterName"].SetOrdinal(0);
            dtTemp.Columns["Issues"].SetOrdinal(1);
            dtTemp.Columns["Complaint"].SetOrdinal(2);

            ClosedXML.Excel.XLWorkbook wbook = new ClosedXML.Excel.XLWorkbook();
            wbook.Worksheets.Add(dtTemp, "tab1");
            // Prepare the response
            HttpResponse httpResponse = Response;
            httpResponse.Clear();
            httpResponse.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
            //Provide you file name here
            httpResponse.AddHeader("content-disposition", "attachment;filename="CampaignReportIssues.xlsx"");

            // Flush the workbook to the Response.OutputStream
            using (MemoryStream memoryStream = new MemoryStream())
            {
                wbook.SaveAs(memoryStream);
                memoryStream.WriteTo(httpResponse.OutputStream);
                memoryStream.Close();
            }
            httpResponse.End();
        }
    }

        // Public
        public void Create(String filePath)
        {
            var workbook = new XLWorkbook();
            var ws = workbook.Worksheets.Add("Merge Cells");

            // Merge a row
            ws.Cell("B2").Value = "Merged Row(1) of Range (B2:D3)";
            ws.Range("B2:D3").Row(1).Merge();

            // Merge a column
            ws.Cell("F2").Value = "Merged Column(1) of Range (F2:G8)";
            ws.Cell("F2").Style.Alignment.WrapText = true;
            ws.Range("F2:G8").Column(1).Merge();

            // Merge a range
            ws.Cell("B4").Value = "Merged Range (B4:D6)";
            ws.Cell("B4").Style.Alignment.Horizontal = XLAlignmentHorizontalValues.Center;
            ws.Cell("B4").Style.Alignment.Vertical = XLAlignmentVerticalValues.Center;
            ws.Range("B4:D6").Merge();

            // Unmerging a range...
            ws.Cell("B8").Value = "Unmerged";
            ws.Range("B8:D8").Merge();
            ws.Range("B8:D8").Unmerge();

            workbook.SaveAs(filePath);
        }
 public static void ExportExcel(Letter[] data)
 {
     try
     {
         var workbook = new XLWorkbook();
         var sheet = workbook.Worksheets.Add("Letters");
         var row = sheet.FirstRow();
         SetHeader(row);
         row = row.RowBelow();
         foreach (var letter in data)
         {
             SetData(row, letter);
             row = row.RowBelow();
         }
         sheet.Columns().AdjustToContents();
         var table = sheet.RangeUsed().CreateTable();
         table.Theme = XLTableTheme.TableStyleMedium15;
         SaveFileDialog dialog = new SaveFileDialog();
         dialog.Filter = "Excel Files (*.xlsx)|*.xlsx";
         dialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
         dialog.FileName = "Letters";
         if (dialog.ShowDialog() != DialogResult.OK) return;
         workbook.SaveAs(dialog.FileName);
         System.Diagnostics.Process.Start(dialog.FileName);
     }
     catch (Exception ex) { MessageBox.Show(ex.Message); }
 }
        public void DataTableExport(DataTable dataTable, string filePath, string title)
        {
            if (string.IsNullOrWhiteSpace(filePath))
                throw new FileNotFoundException("Incorrect file path.");

            if ((dataTable == null) || (dataTable.Rows.Count == 0))
                throw new ArgumentException("Empty data table.");

            var workbook = new XLWorkbook();
            var worksheet = workbook.Worksheets.Add(title);

            if (IncludeTitle)
            {
                worksheet.Cell(1, 1).Value = title;
                worksheet.Range(1, 1, 1, dataTable.Columns.Count).Merge().AddToNamed("Titles");

                var titlesStyle = workbook.Style;
                titlesStyle.Font.Bold = true;
                titlesStyle.Font.FontSize = 16;
                titlesStyle.Alignment.Horizontal = XLAlignmentHorizontalValues.Center;
                titlesStyle.Fill.BackgroundColor = XLColor.Cyan;
                workbook.NamedRanges.NamedRange("Titles").Ranges.Style = titlesStyle;
            }
            worksheet.Cell(2, 1).InsertTable(dataTable.AsEnumerable());

            worksheet.Columns().AdjustToContents();

            workbook.SaveAs(filePath);
        }

        // Public
        public void Create(String filePath)
        {
            var workbook = new XLWorkbook();
            var ws = workbook.Worksheets.Add("Inserting Rows");

            // Color the entire spreadsheet using rows
            ws.Rows().Style.Fill.BackgroundColor = XLColor.LightCyan;

            // Put a value in a few cells
            foreach (var r in Enumerable.Range(1, 5))
                foreach (var c in Enumerable.Range(1, 5))
                    ws.Cell(r, c).Value = "X";

            var blueRow = ws.Row(2);
            var redRow = ws.Row(5);

            blueRow.Style.Fill.BackgroundColor = XLColor.Blue;
            blueRow.InsertRowsBelow(2);

            redRow.Style.Fill.BackgroundColor = XLColor.Red;
            redRow.InsertRowsAbove(2);

            ws.Columns(3, 4).Style.Fill.BackgroundColor = XLColor.Orange;
            ws.Range("A2:A4").InsertRowsBelow(2);
            ws.Range("B2:B4").InsertRowsAbove(2);
            ws.Range("C2:C4").InsertRowsBelow(2);
            ws.Range("D2:D4").InsertRowsAbove(2);

            workbook.SaveAs(filePath);
        }
        public static void WriteBeaches()
        {
            var workbook = new XLWorkbook();
            var worksheet = workbook.Worksheets.Add("Плажове");

            for(int i = 0; i < Beach.beaches.Count; i++)
            {
                Beach current = Beach.beaches[i];
                int rowIdx = i + 2;
                worksheet.Cell(f("A", rowIdx)).Value = current.name;
                worksheet.Cell(f("B", rowIdx)).Value = current.location;
                worksheet.Cell(f("C", rowIdx)).Value = current.nCar;
                worksheet.Cell(f("D", rowIdx)).Value = current.nCity;
                worksheet.Cell(f("E", rowIdx)).Value = current.nFoot;

                worksheet.Cell(f("F", rowIdx)).Value = current.facilties[0];
                worksheet.Cell(f("G", rowIdx)).Value = current.facilties[1];
                worksheet.Cell(f("H", rowIdx)).Value = current.facilties[2];
                worksheet.Cell(f("I", rowIdx)).Value = current.facilties[3];

                worksheet.Cell(f("J", rowIdx)).Value = current.Density;
                worksheet.Cell(f("K", rowIdx)).Value = current.Polution;
                worksheet.Cell(f("L", rowIdx)).Value = current.Grade;
                worksheet.Cell(f("M", rowIdx)).Value = current.People;
            }

            workbook.SaveAs("ало.xlsx");
        }

        public void Export(string filePath)
        {
            using (var workbook = new XLWorkbook(XLEventTracking.Disabled))
            {

                IEnumerable<CultureInfo> cultures = null;
                if (Cultures != null)
                    cultures = Cultures.Select(vc => vc.Culture);
                else
                    cultures = Solution.Cultures.Keys;

                IEnumerable<VSProject> projects = Projects;
                if (Projects == null)
                    projects = (IEnumerable<VSProject>)Solution.Projects.Values;

                foreach (var project in projects)
                {
                    var data = GetData(project, cultures);

                    if (IncludeProjectsWithoutTranslations || data.Count() > 0)
                        AddProject(project, workbook, cultures, data);
                }

                workbook.SaveAs(filePath);
            }
        }
    public static void ExportToExcel(DataSet ds, string sheetName, System.Web.UI.Page page)
    {
        if (ds.Tables.Count > 0)
        {
            if (ds.Tables[0].Rows.Count <= 0)
            {
                ds.Tables[0].Rows.Add(ds.Tables[0].NewRow());
            }
        }


        ClosedXML.Excel.XLWorkbook wbook = new ClosedXML.Excel.XLWorkbook();
        wbook.Worksheets.Add(ds.Tables[0], sheetName);
        // Prepare the response
        HttpResponse httpResponse = page.Response;

        httpResponse.Clear();
        httpResponse.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
        //Provide you file name here
        httpResponse.AddHeader("content-disposition", "attachment;filename='" + sheetName + ".xlsx'");

        // Flush the workbook to the Response.OutputStream
        using (MemoryStream memoryStream = new MemoryStream())
        {
            wbook.SaveAs(memoryStream);
            memoryStream.WriteTo(httpResponse.OutputStream);
            memoryStream.Close();
        }

        httpResponse.End();
    }
 public void Create(String filePath)
 {
     var workbook = new XLWorkbook();
     var worksheet = workbook.Worksheets.Add("Sample Sheet");
     worksheet.Cell("A1").Value = "Hello World!";
     workbook.SaveAs(filePath);
 }
        public void Create(string filePath)
        {
            string tempFile = ExampleHelper.GetTempFilePath(filePath);
            try
            {
                //Note: Prepare
                {
                    var workbook = new XLWorkbook();
                    workbook.Worksheets.Add("1");
                    workbook.Worksheets.Add("2");
                    workbook.Worksheets.Add("3");
                    workbook.Worksheets.Add("4");
                    workbook.SaveAs(tempFile);
                }

                //Note: Delate few worksheet
                {
                    var workbook = new XLWorkbook(tempFile);
                    workbook.Worksheets.Delete("1");
                    workbook.Worksheets.Delete("2");
                    workbook.SaveAs(filePath);
                }
            }
            finally
            {
                if (File.Exists(tempFile))
                {
                    File.Delete(tempFile);
                }
            }
        }

    protected void btExcel_Click(object sender, EventArgs e)
    {
        string sql = "";

        sql += @"select * from tb_DetailB ORDER BY NgayDangKy DESC";
        DataTable table = Connect.GetTable(sql);

        ClosedXML.Excel.XLWorkbook wbook = new ClosedXML.Excel.XLWorkbook();
        wbook.Worksheets.Add(table, "tab1");
        // Prepare the response
        HttpResponse httpResponse = Response;

        httpResponse.Clear();
        httpResponse.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
        //Provide you file name here
        httpResponse.AddHeader("content-disposition", "attachment;filename="DanhSachDangKyKhaiSinh(" + DateTime.Now.ToString("dd_MM_yyyy_HH_mm_ss") + ").xlsx"");
        // Flush the workbook to the Response.OutputStream
        using (MemoryStream memoryStream = new MemoryStream())
        {
            wbook.SaveAs(memoryStream);
            memoryStream.WriteTo(httpResponse.OutputStream);
            memoryStream.Close();
        }

        httpResponse.End();
    }

        public void Create(string filePath)
        {
            var tempFile = ExampleHelper.GetTempFilePath(filePath);
            try
            {
                new BasicTable().Create(tempFile);
                var workbook = new XLWorkbook(tempFile);
                var ws = workbook.Worksheet(1);

                // Define a range with the data
                var firstTableCell = ws.FirstCellUsed();
                var lastTableCell = ws.LastCellUsed();
                var rngData = ws.Range(firstTableCell.Address, lastTableCell.Address);

                // Copy the table to another worksheet
                var wsCopy = workbook.Worksheets.Add("Contacts Copy");
                wsCopy.Cell(1, 1).Value = rngData;

                workbook.SaveAs(filePath);
            }
            finally
            {
                if (File.Exists(tempFile))
                {
                    File.Delete(tempFile);
                }
            }
        }

        // Public
        public void Create(String filePath)
        {
            #region Create case
            {
                var workbook = new XLWorkbook();
                var ws = workbook.Worksheets.Add("Delete red rows");

                // Put a value in a few cells
                foreach (var r in Enumerable.Range(1, 5))
                    foreach (var c in Enumerable.Range(1, 5))
                        ws.Cell(r, c).Value = string.Format("R{0}C{1}", r, c);

                var blueRow = ws.Rows(1, 2);
                var redRow = ws.Row(5);

                blueRow.Style.Fill.BackgroundColor = XLColor.Blue;

                redRow.Style.Fill.BackgroundColor = XLColor.Red;
                workbook.SaveAs(filePath);
            }
            #endregion

            #region Remove rows
            {
                var workbook = new XLWorkbook(filePath);
                var ws = workbook.Worksheets.Worksheet("Delete red rows");

                ws.Rows(1, 2).Delete();
                workbook.Save();
            }
            #endregion
        }
        public void Build(Tree features)
        {
            if (Log.IsInfoEnabled)
            {
                Log.Info("Writing Excel workbook to {0}", this.configuration.OutputFolder.FullName);
            }

            string spreadsheetPath = this.fileSystem.Path.Combine(this.configuration.OutputFolder.FullName, "features.xlsx");
            using (var workbook = new XLWorkbook())
            {
                foreach (var node in features)
                {
                    var featureDirectoryTreeNode =
                        node as FeatureNode;
                    if (featureDirectoryTreeNode != null)
                    {
                        IXLWorksheet worksheet =
                            workbook.AddWorksheet(
                                this.excelSheetNameGenerator.GenerateSheetName(
                                    workbook,
                                    featureDirectoryTreeNode
                                        .Feature));
                        this.excelFeatureFormatter.Format(
                            worksheet,
                            featureDirectoryTreeNode.Feature);
                    }
                }

                this.excelTableOfContentsFormatter.Format(workbook, features);

                workbook.SaveAs(spreadsheetPath);
            }
        }

        private static void CreateExcelFile(ChromeDriver driver)
        {
            var upcomingEvents = driver.FindElementsByCssSelector(".event.active");

            var wb = new XLWorkbook();
            var ws = wb.Worksheets.Add("Games");

            ws.Cell("A1").Value = "Games";
            ws.Cell("B1").Value = "Home";
            ws.Cell("C1").Value = "Draw";
            ws.Cell("D1").Value = "Away";

            for (int i = 0; i < upcomingEvents.Count; i++)
            {
                string eventName = upcomingEvents[i].FindElement(By.ClassName("eventName")).Text;
                string homeOdd = upcomingEvents[i].FindElement(By.ClassName("home")).Text;
                string drawOdd = upcomingEvents[i].FindElement(By.ClassName("draw")).Text;
                string awayOdd = upcomingEvents[i].FindElement(By.ClassName("away")).Text;

                ws.Cell("A" + (i + 2)).Value = eventName;
                ws.Cell("B" + (i + 2)).Value = homeOdd;
                ws.Cell("C" + (i + 2)).Value = drawOdd;
                ws.Cell("D" + (i + 2)).Value = awayOdd;
            }

            // Beautify
            ws.Range("A1:D1").Style.Font.Bold = true;
            ws.Columns().AdjustToContents();

            wb.SaveAs("../../../../Events.xlsx");
        }

        private byte[] GenerateReport(List<RsvpReportRow> users)
        {

                

                var workbook = new XLWorkbook();
                var worksheet = workbook.Worksheets.Add("RSVP Users");
                worksheet.Cell("A1").Value = "First Name";
                worksheet.Cell("B1").Value = "Last Name";
                worksheet.Cell("C1").Value = "Email";
                worksheet.Cell("D1").Value = "Date RSVPed";

                int rowCount = 1;
                foreach (var row in users)
                {
                    rowCount++;

                    worksheet.Cell("A" + rowCount).Value = row.FirstName;
                    worksheet.Cell("B" + rowCount).Value = row.LastName;
                    worksheet.Cell("C" + rowCount).Value = row.EmailAddress;
                    worksheet.Cell("D" + rowCount).Value = row.RsvpDate.ToLongTimeString();
                }
                       
            byte[] results;
            using( MemoryStream memory = new MemoryStream())
            {
                workbook.SaveAs(memory);

                results = memory.ToArray();
            };

            return results;
            
        }
    protected void BtnExcel_Click(object sender, EventArgs e)
    {
        Db.DAOrdenes OBJ = new Db.DAOrdenes();
        //GcExportar.DataSource = OBJ.Reporte(txtOrden.Value.Trim(), ddlTipoResultado.SelectedValue.ToString(),
        //datavalue.Value.ToString(), datavalue2.Value.ToString(), ddlMotorizado.SelectedValue.ToString(), ddlSucursal.SelectedValue.ToString());
        //GcExportar.DataBind();

        DataTable dt_report = new DataTable();

        dt_report = OBJ.Reporte(txtOrden.Value.Trim(), ddlTipoResultado.SelectedValue.ToString(),
                                datavalue.Value.ToString(), datavalue2.Value.ToString(), ddlMotorizado.SelectedValue.ToString(), ddlSucursal.SelectedValue.ToString());

        ClosedXML.Excel.XLWorkbook wbook = new ClosedXML.Excel.XLWorkbook();
        wbook.Worksheets.Add(dt_report, "reporte");
        // Preparar la respuesta
        HttpResponse httpResponse = Response;

        httpResponse.Clear();
        httpResponse.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
        // Proporcione su nombre de archivo aquí
        httpResponse.AddHeader("content-disposition", "attachment;filename="Reporte_Pedido " + DateTime.Now + ".xlsx"");
        //Vacíe el libro de trabajo al Response.OutputStream
        using (MemoryStream memoryStream = new MemoryStream())
        {
            wbook.SaveAs(memoryStream);
            memoryStream.WriteTo(httpResponse.OutputStream);
            memoryStream.Close();
        }

        httpResponse.End();
    }

        // Public
        public void Create(String filePath)
        {
            var workbook = new XLWorkbook();
            var ws = workbook.Worksheets.Add("Inserting Columns");

            // Color the entire spreadsheet using columns
            ws.Columns().Style.Fill.BackgroundColor = XLColor.LightCyan;

            // Put a value in a few cells
            foreach (var r in Enumerable.Range(1, 5))
                foreach (var c in Enumerable.Range(1, 5))
                    ws.Cell(r, c).Value = "X";

            var blueColumn = ws.Column(2);
            var redColumn = ws.Column(5);

            blueColumn.Style.Fill.BackgroundColor = XLColor.Blue;
            blueColumn.InsertColumnsAfter(2);

            redColumn.Style.Fill.BackgroundColor = XLColor.Red;
            redColumn.InsertColumnsBefore(2);

            ws.Rows(3, 4).Style.Fill.BackgroundColor = XLColor.Orange;
            ws.Range("B1:D1").InsertColumnsAfter(2);
            ws.Range("B2:D2").InsertColumnsBefore(2);
            ws.Range("B3:D3").InsertColumnsAfter(2);
            ws.Range("B4:D4").InsertColumnsBefore(2);

            workbook.SaveAs(filePath);
        }
 public static void Basic()
 {
     var wb = new XLWorkbook();
     var ws = wb.AddWorksheet("Worksheet Name");
     ws.Cell("A1").Value = Data;
     wb.SaveAs(MethodBase.GetCurrentMethod().Name + ".xlsx");
 }
        //---------------------------------------------------------//
        //      Method
        //---------------------------------------------------------//
        public void ExcelFile()
        {
            string tempFile = Folder.DefaultLocation() + @".~temp.xlsx";

            Cursor.Current = Cursors.WaitCursor;                // マウスカーソルを砂時計(Wait)

            try
            {
                using (oWBook = new XLWorkbook(fileName))
                {
                    // 編集
                    oWSheet = oWBook.Worksheet(1);      // シートを開く
                    editReviewData(pubDat);

                    // 保存
                    oWBook.SaveAs(tempFile);                    // Excel保存
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                Cursor.Current = Cursors.Default;               // マウスカーソルを戻す
                return;
            }

            Cursor.Current = Cursors.Default;                        // マウスカーソルを戻す
            System.Diagnostics.Process.Start("Excel.exe", tempFile); // 表示用Excel
        }

        public void Create(String filePath)
        {
            var workbook = new XLWorkbook();
            var ws = workbook.Worksheets.Add("Style Worksheet");

            ws.Style.Font.Bold = true;
            ws.Style.Font.FontColor = XLColor.Red;
            ws.Style.Fill.BackgroundColor = XLColor.Cyan;

            // The following cells will be bold and red
            // because we've specified those attributes to the entire worksheet
            ws.Cell(1, 1).Value = "Test";
            ws.Cell(1, 2).Value = "Case";

            // Here we'll change the style of a single cell
            ws.Cell(2, 1).Value = "Default";
            ws.Cell(2, 1).Style = XLWorkbook.DefaultStyle;

            // Let's play with some rows
            ws.Row(4).Style = XLWorkbook.DefaultStyle;
            ws.Row(4).Height = 20;
            ws.Rows(5, 6).Style = XLWorkbook.DefaultStyle;
            ws.Rows(5, 6).Height = 20;

            // Let's play with some columns
            ws.Column(4).Style = XLWorkbook.DefaultStyle;
            ws.Column(4).Width = 5;
            ws.Columns(5, 6).Style = XLWorkbook.DefaultStyle;
            ws.Columns(5, 6).Width = 5;

            workbook.SaveAs(filePath);
        }

        public void Create(string filePath)
        {
            string tempFile = ExampleHelper.GetTempFilePath(filePath);
            try
            {
                new BasicTable().Create(tempFile);
                var workbook = new XLWorkbook(tempFile);

                var ws = workbook.Worksheet(1);

                var rngTable = ws.Range("B2:F6");

                rngTable.Transpose(XLTransposeOptions.MoveCells);

                ws.Columns().AdjustToContents();

                workbook.SaveAs(filePath);
            }
            finally
            {
                if (File.Exists(tempFile))
                {
                    File.Delete(tempFile);
                }
            }
        }

        public void Create(string filePath)
        {
            string tempFile1 = ExampleHelper.GetTempFilePath(filePath);
            string tempFile2 = ExampleHelper.GetTempFilePath(filePath);
            try
            {
                new UsingTables().Create(tempFile1);
                var wb = new XLWorkbook(tempFile1);

                var wsSource = wb.Worksheet(1);
                // Copy the worksheet to a new sheet in this workbook
                wsSource.CopyTo("Copy");

                // We're going to open another workbook to show that you can
                // copy a sheet from one workbook to another:
                new BasicTable().Create(tempFile2);
                var wbSource = new XLWorkbook(tempFile2);
                wbSource.Worksheet(1).CopyTo(wb, "Copy From Other");

                // Save the workbook with the 2 copies
                wb.SaveAs(filePath);
            }
            finally
            {
                if (File.Exists(tempFile1))
                {
                    File.Delete(tempFile1);
                }
                if (File.Exists(tempFile2))
                {
                    File.Delete(tempFile2);
                }
            }
        }

 // Public
 public void Create(String filePath)
 {
     var wb = new XLWorkbook();
     var ws = wb.Worksheets.Add("Sheet1");
     ws.Cell(1, 1).Value = "X";
     ws.Cell(1, 1).Clear();
     wb.SaveAs(filePath);
 }
 public static void Closeit()
 {
     var workbook = new XLWorkbook();
     var worksheet = workbook.Worksheets.Add("Rippit");
     worksheet.Cell("B5").Value = "Snart that!";
     //worksheet.Column("A")
     workbook.SaveAs("Yosup.xlsx");
 }

    private static void DuplicateExcelSheetByEPPlus(string baseDir, string bookPath)
    {
        var outPath = Path.Combine(baseDir, "Book1 - ClosedXML.xlsx");

        using (var book = new ClosedXML.Excel.XLWorkbook(bookPath))
        {
            book.Worksheet("Sheet1").CopyTo("Sheet2");
            book.SaveAs(outPath);
        }
    }
        //作業割り当て表Excelファイル出力
        public void save_asignlist_xlsx_as(List <List <string> > data, List <string> categories, string filename)
        {
            _write_log __write_log = write_log;

            try
            {
                using (var wb = new ClosedXML.Excel.XLWorkbook())
                {
                    var ws = wb.Worksheets.Add("Sheet1");

                    //行のループ
                    for (int i = 0; i < data.Count; i++)
                    {
                        List <string> row = (List <string>)data[i];

                        //列のループ
                        for (int j = 0; j < row.Count; j++)
                        {
                            string col = (string)row[j];
                            ws.Cell(i + 1, j + 1).SetValue <string>(fetch_overflow_characters(col));
                            ws.Cell(i + 1, j + 1).Style.Border.TopBorder    = XLBorderStyleValues.Thin;
                            ws.Cell(i + 1, j + 1).Style.Border.BottomBorder = XLBorderStyleValues.Thin;
                            ws.Cell(i + 1, j + 1).Style.Border.LeftBorder   = XLBorderStyleValues.Thin;
                            ws.Cell(i + 1, j + 1).Style.Border.RightBorder  = XLBorderStyleValues.Thin;
                            ws.Cell(i + 1, j + 1).Style.Font.FontName       = "MS Pゴシック";
                            ws.Cell(i + 1, j + 1).Style.Alignment.SetVertical(XLAlignmentVerticalValues.Top);
                        }

                        if (i == 0)
                        {
                            int maxcol = row.Count;
                            for (int z = 0; z < categories.Count; z++)
                            {
                                ws.Cell(i + 1, maxcol + (z + 1)).SetValue <string>((string)categories[z]);
                                ws.Cell(i + 1, maxcol + (z + 1)).Style.Border.TopBorder    = XLBorderStyleValues.Thin;
                                ws.Cell(i + 1, maxcol + (z + 1)).Style.Border.BottomBorder = XLBorderStyleValues.Thin;
                                ws.Cell(i + 1, maxcol + (z + 1)).Style.Border.LeftBorder   = XLBorderStyleValues.Thin;
                                ws.Cell(i + 1, maxcol + (z + 1)).Style.Border.RightBorder  = XLBorderStyleValues.Thin;
                                ws.Cell(i + 1, maxcol + (z + 1)).Style.Font.FontName       = "MS Pゴシック";
                                ws.Cell(i + 1, maxcol + (z + 1)).Style.Alignment.SetVertical(XLAlignmentVerticalValues.Top);
                                ws.Cell(i + 1, maxcol + (z + 1)).Style.Alignment.TopToBottom = true;
                            }
                        }
                    }

                    wb.SaveAs(filename);
                    main_form.Invoke(__write_log, "保存に成功しました。(" + filename + ")");
                }
            }
            catch (Exception ex)
            {
                main_form.Invoke(__write_log, "【エラー】" + ex.Message);
                return;
            }
        }

    static void Main(string[] args)
    {
        DataTable table = new DataTable("test");

        table.Columns.Add();
        table.Columns.Add();
        table.Rows.Add("1", "2");
        table.Rows.Add("3", "4");
        ClosedXML.Excel.XLWorkbook workbook = new ClosedXML.Excel.XLWorkbook();
        workbook.Worksheets.Add(table);
        workbook.SaveAs("D:\test.xlsx");
    }
        public void ExportExcel(DataSet ds, string destination)
        {
            var workbook = new ClosedXML.Excel.XLWorkbook();

            foreach (DataTable dt in ds.Tables)
            {
                var worksheet = workbook.Worksheets.Add(dt.TableName);
                worksheet.Cell(1, 1).InsertTable(dt);
                worksheet.Columns().AdjustToContents();
            }
            workbook.SaveAs(destination);
            workbook.Dispose();
        }

        // Wakamatsu
        // Wakamatsu 20170301
        //private string editExcelSheet(string sheetName, DataTable dt, FormatSet[] FormatSet)
        private string editExcelSheet(string FileName, string sheetName, DataTable dt, FormatSet[] FormatSet)
        {
            // Wakamatsu 20170301
            //string tempFile = Folder.MyDocuments() + @"" + sheetName + DateTime.Now.ToString("yyyyMMddHHmmss") + ".xlsx";
            string tempFile = Folder.MyDocuments() + @"" + FileName + DateTime.Now.ToString("yyyyMMddHHmmss") + ".xlsx";

            // Wakamatsu 20170301
            Cursor.Current = Cursors.WaitCursor;   // マウスカーソルを砂時計(Wait)

            if (System.IO.File.Exists(fileName) == false)
            {
                Cursor.Current = Cursors.Default;  // マウスカーソルを戻す
                return("× テンプレートファイルが存在しません。rn");
            }

            // Wakamatsu 20170322
            //using(oWBook = new XLWorkbook(fileName))
            //{
            try
            {
                // Wakamatsu 20170322
                using (oWBook = new XLWorkbook(fileName))
                {
                    oWSheet = oWBook.Worksheet(sheetName);

                    // Excelファイル出力
                    if (MasterExport(dt, FormatSet) == true)
                    {
                        oWBook.SaveAs(tempFile);          // Excel保存
                        Cursor.Current = Cursors.Default; // マウスカーソルを戻す
                        return("○ Excel出力が正常に終了しました。rn" +
                               " " + dt.Rows.Count + "件のデータを出力しました。rn");
                    }
                    else
                    {
                        Cursor.Current = Cursors.Default;  // マウスカーソルを戻す
                        return("× Excel出力ができませんでした。rn");
                    }
                }
            }
            catch (Exception ex)
            {
                Cursor.Current = Cursors.Default;  // マウスカーソルを戻す
                // Wakamatsu 20170322
                //MessageBox.Show(ex.Message);
                //return "× Excel出力ができませんでした。rn";
                return(ex.Message + "rn× Excel出力ができませんでした。rn");
                // Wakamatsu 20170322
            }
            //}
        }

        private static void getReport()
        {
            DAL       objDAL         = new DAL();
            DataTable dt             = new DataTable();
            DataTable dtConfigReport = getConfig("Report");
            string    filePath       = ConfigurationManager.AppSettings["folderPath"].ToString() + "WeeklyReport.xlsx";
            string    Query          = "usp_get_WeeklyReportData";

            objDAL.CommandText = Query;
            dt = objDAL.ExecuteDataSet().Tables[0];
            XLWorkbook wb = new ClosedXML.Excel.XLWorkbook();

            wb.Worksheets.Add(dt);
            wb.SaveAs(filePath);
            sendEmail("", dtConfigReport, "", filePath);
        }
        private void btnFullMetal_Click(object sender, EventArgs e)
        {
            string strKeyWord = "毒蜥级";
            string strPath    = Application.StartupPath + "\EXCEL\" + strKeyWord + "制造方案";

            Excel.XLWorkbook   xFile   = new Excel.XLWorkbook();
            Excel.IXLWorksheet xLSheet = xFile.AddWorksheet();

            int nRow = 1;
            int nCol = 1;

            OutputBluePrintResult(xLSheet, strKeyWord, ref nRow, ref nCol);

            xFile.SaveAs(strPath + ".xlsx");
            MessageBox.Show("计算完成,路径:" + strPath);
        }
        protected virtual void Response()
        {
            HttpResponse _response = HttpContext.Current.Response;

            _response.ClearContent();
            _response.Buffer = true;
            _response.AddHeader("content-disposition", string.Format("attachment; filename={0}.xlsx", this._filename ?? (new Guid()).ToString()));
            _response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
            _response.Charset     = "";
            using (MemoryStream MyMemoryStream = new MemoryStream())
            {
                workbook.SaveAs(MyMemoryStream);
                MyMemoryStream.WriteTo(_response.OutputStream);
                _response.Flush();
                _response.End();
            }
        }

        private static async Task <XLWorkbook> BuildWorkbook(List <CommonLookup> headerfields, SqlDataReader reader, SqlConnection connection, string filename)
        {
            Console.WriteLine("BuildWorkbook");
            //now let's build a spreadsheet
            XLWorkbook workbook = null;

            var t = Task.Run(() =>
            {
                workbook      = new ClosedXML.Excel.XLWorkbook();
                var worksheet = workbook.Worksheets.Add("Sheet1");

                int row = 1;
                int idx = 1;
                foreach (CommonLookup cl in headerfields)
                {
                    worksheet.Row(row).Cell(idx).SetDataType(XLCellValues.Text);
                    worksheet.Row(row).Cell(idx).SetValue(cl.Code);
                    idx++;
                }

                row = row + 1;
                idx = 1;
                while (reader.Read() && row < 100000)
                {
                    foreach (CommonLookup cl in headerfields)
                    {
                        worksheet.Row(row).Cell(idx).SetDataType(XLCellValues.Text);
                        worksheet.Row(row).Cell(idx).SetValue(reader[cl.CodeDesc].ToString());
                        idx++;
                    }
                    row++;
                    idx = 1;
                }

                workbook.SaveAs(filename);
            });

            t.Wait();

            Console.WriteLine("Finished - BuildingWorkbook");
            return(workbook);
        }

        public void Stampa(Pagamento pagamentoSel)
        {
            using (var uof = new UnitOfWork())
            {
                var pagamento = uof.PagamentoRepository.Find(a => a.ID == pagamentoSel.ID)
                                .First();
                var righePag = uof.PagamentoRepository.Find(a => a.IDPagamentoMaster == pagamentoSel.IDPagamentoMaster &&
                                                            a.ID != pagamentoSel.ID).OrderBy(a => a.DataRata).ToList();

                ImpostaCampiTestata(pagamento);


                ImpostaDettaglio(righePag, pagamento);
            }

            var newfile = Path.Combine(System.IO.Path.GetTempPath(),
                                       DateTime.Now.Ticks.ToString() + "_Pag.xlsx");

            _wb.SaveAs(newfile);
            Process.Start(newfile);
        }

        //Excelファイルに出力
        public void save_xlsx_as(List <List <string> > data, string filename)
        {
            d_messenger message = new d_messenger(w_messenger);

            try
            {
                using (var wb = new ClosedXML.Excel.XLWorkbook())
                {
                    var ws = wb.Worksheets.Add("Sheet1");

                    //行のループ
                    for (int i = 0; i < data.Count; i++)
                    {
                        List <string> row = (List <string>)data[i];

                        //列のループ
                        for (int j = 0; j < row.Count; j++)
                        {
                            string col = (string)row[j];
                            ws.Cell(i + 1, j + 1).SetValue <string>(fetch_overflow_characters(col));
                            ws.Cell(i + 1, j + 1).Style.Border.TopBorder    = XLBorderStyleValues.Thin;
                            ws.Cell(i + 1, j + 1).Style.Border.BottomBorder = XLBorderStyleValues.Thin;
                            ws.Cell(i + 1, j + 1).Style.Border.LeftBorder   = XLBorderStyleValues.Thin;
                            ws.Cell(i + 1, j + 1).Style.Border.RightBorder  = XLBorderStyleValues.Thin;
                            ws.Cell(i + 1, j + 1).Style.Font.FontName       = "MS Pゴシック";
                            ws.Cell(i + 1, j + 1).Style.Alignment.SetVertical(XLAlignmentVerticalValues.Top);
                        }
                    }

                    wb.SaveAs(filename);
                    main_form.Invoke(message, "保存に成功しました。(" + filename + ")");
                }
            }
            catch (Exception ex)
            {
                main_form.Invoke(message, "【エラー】" + ex.Message);
                return;
            }
        }

        private void toolStripButton1_Click(object sender, EventArgs e)
        {
            if (gridVista.SelectedRows.Count != 0)
            {
                try
                {
                    string             carpeta = System.Configuration.ConfigurationManager.AppSettings[companySelected() + "_directorio"].ToString();
                    DcemVwContabilidad item    = (DcemVwContabilidad)gridVista.SelectedRows[0].DataBoundItem;
                    if (item != null)
                    {
                        var    iTipoDoc      = lParametros.Where(x => x.Tipo == item.tipodoc);
                        string nombreArchivo = iTipoDoc.First().Archivo;
                        nombreArchivo = Path.GetFileNameWithoutExtension(nombreArchivo) + "_" + DateTime.Now.ToString("yyyyMMdd HHmmss");
                        string archivo = Path.Combine(carpeta, nombreArchivo + ".xlsx");

                        object    items   = mostrarContenido(item.year1, item.periodid, item.tipodoc);
                        DataTable dtItems = ContabilidadElectronicaPresentacion.ConvierteLinqQueryADataTable((IEnumerable <dynamic>)items);
                        var       wb      = new ClosedXML.Excel.XLWorkbook();

                        dtItems.TableName = "test";
                        wb.Worksheets.Add(dtItems);
                        //wb.Worksheet(1).Cell("B1").Value = "0";

                        //wb.Worksheet(1).Column(2).CellsUsed().SetDataType(XLDataType.Number);

                        //wb.Worksheet(1).Cell("B1").Value = "Saldo Inicial";

                        wb.SaveAs(archivo);
                        UtilitarioArchivos.AbrirArchivo(archivo);
                        lblProcesos.Text = "Archivo guardado en: " + archivo;
                    }
                }
                catch (Exception exl)
                {
                    grid.DataSource = null;
                    lblError.Text   = exl.Message;
                }
            }
        }

        //---------------------------------------------------------//
        // SubRoutine
        //---------------------------------------------------------//
        private void editExcelSheet(string sheetName, PublishData pd, DataGridView dgv)
        {
            string tempFile = Folder.DefaultLocation() + @".~temp.xlsx";

            Cursor.Current = Cursors.WaitCursor;   // マウスカーソルを砂時計(Wait)

            try
            {
                using (oWBook = new XLWorkbook(fileName))
                {
                    oWSheet = oWBook.Worksheet(sheetName);
                    switch (sheetName)
                    {
                    case "ContractWorks":
                        editContractWorks(pd, dgv);
                        break;

                    case "ContractSummary":
                        editContractSummary(pd, dgv);
                        break;

                    default:
                        break;
                    }
                    oWBook.SaveAs(tempFile);      // Excel保存
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                Cursor.Current = Cursors.Default;  // マウスカーソルを戻す
                return;
            }

            Cursor.Current = Cursors.Default;                        // マウスカーソルを戻す
            System.Diagnostics.Process.Start("Excel.exe", tempFile); // 表示用Excel
        }

        //カテゴリ別検査項目一覧表Excelファイル作成
        public void save_category_by_details_xlsx(List <List <object> > data, string filename)
        {
            _write_log __write_log = write_log;

            try
            {
                using (var wb = new ClosedXML.Excel.XLWorkbook())
                {
                    var ws = wb.Worksheets.Add("検査項目一覧");

                    //ヘッダー行
                    ws.Cell(1, 1).SetValue <string>("カテゴリ");
                    ws.Cell(1, 2).SetValue <string>("項番");
                    ws.Cell(1, 3).SetValue <string>("検査内容");
                    ws.Cell(1, 4).SetValue <string>("レベル/達成基準/実装番号");
                    double[] col_wd = { 15, 5, 91.9, 68 };
                    for (int cx = 1; cx <= 4; cx++)
                    {
                        ws.Cell(1, cx).Style.Border.TopBorder    = XLBorderStyleValues.Thin;
                        ws.Cell(1, cx).Style.Border.BottomBorder = XLBorderStyleValues.Thin;
                        ws.Cell(1, cx).Style.Border.LeftBorder   = XLBorderStyleValues.Thin;
                        ws.Cell(1, cx).Style.Border.RightBorder  = XLBorderStyleValues.Thin;
                        ws.Cell(1, cx).Style.Alignment.SetVertical(XLAlignmentVerticalValues.Top);
                        ws.Cell(1, cx).Style.Alignment.SetHorizontal(XLAlignmentHorizontalValues.Center);
                        ws.Cell(1, cx).Style.Font.Bold = true;
                        ws.Column(cx).Width            = col_wd[cx - 1];
                    }

                    for (int i = 0; i < data.Count; i++)
                    {
                        var           row = data[i];
                        string        v0  = (string)row[0];
                        string        v1  = (string)row[1];
                        string        v2  = (string)row[2];
                        string        v3  = "";
                        List <string> gs  = (List <string>)row[3];
                        int           nx  = 0;

                        ws.Cell(i + 2, 1).SetValue <string>(v0);
                        ws.Cell(i + 2, 1).Style.Border.TopBorder    = XLBorderStyleValues.Thin;
                        ws.Cell(i + 2, 1).Style.Border.BottomBorder = XLBorderStyleValues.Thin;
                        ws.Cell(i + 2, 1).Style.Border.LeftBorder   = XLBorderStyleValues.Thin;
                        ws.Cell(i + 2, 1).Style.Border.RightBorder  = XLBorderStyleValues.Thin;
                        ws.Cell(i + 2, 1).Style.Alignment.SetVertical(XLAlignmentVerticalValues.Top);

                        ws.Cell(i + 2, 2).SetValue <string>(v1);
                        ws.Cell(i + 2, 2).Style.Border.TopBorder    = XLBorderStyleValues.Thin;
                        ws.Cell(i + 2, 2).Style.Border.BottomBorder = XLBorderStyleValues.Thin;
                        ws.Cell(i + 2, 2).Style.Border.LeftBorder   = XLBorderStyleValues.Thin;
                        ws.Cell(i + 2, 2).Style.Border.RightBorder  = XLBorderStyleValues.Thin;
                        ws.Cell(i + 2, 2).Style.Alignment.SetVertical(XLAlignmentVerticalValues.Top);

                        ws.Cell(i + 2, 3).SetValue <string>(v2);
                        ws.Cell(i + 2, 3).Style.Border.TopBorder    = XLBorderStyleValues.Thin;
                        ws.Cell(i + 2, 3).Style.Border.BottomBorder = XLBorderStyleValues.Thin;
                        ws.Cell(i + 2, 3).Style.Border.LeftBorder   = XLBorderStyleValues.Thin;
                        ws.Cell(i + 2, 3).Style.Border.RightBorder  = XLBorderStyleValues.Thin;
                        ws.Cell(i + 2, 3).Style.Alignment.SetVertical(XLAlignmentVerticalValues.Top);
                        ws.Cell(i + 2, 3).Style.Alignment.WrapText = true;
                        foreach (string tx in gs)
                        {
                            v3 += tx;
                            if (nx != (gs.Count - 1))
                            {
                                v3 += "rn";
                            }
                            nx++;
                        }
                        ws.Cell(i + 2, 4).SetValue <string>(v3);
                        ws.Cell(i + 2, 4).Style.Border.TopBorder    = XLBorderStyleValues.Thin;
                        ws.Cell(i + 2, 4).Style.Border.BottomBorder = XLBorderStyleValues.Thin;
                        ws.Cell(i + 2, 4).Style.Border.LeftBorder   = XLBorderStyleValues.Thin;
                        ws.Cell(i + 2, 4).Style.Border.RightBorder  = XLBorderStyleValues.Thin;
                        ws.Cell(i + 2, 4).Style.Alignment.SetVertical(XLAlignmentVerticalValues.Top);
                        ws.Cell(i + 2, 4).Style.Alignment.WrapText = true;
                    }

                    wb.SaveAs(filename);
                    main_form.Invoke(__write_log, "保存に成功しました。(" + filename + ")");
                }
            }
            catch (Exception ex)
            {
                main_form.Invoke(__write_log, "【エラー】" + ex.Message);
                return;
            }
        }

        public ActionResult ReporteServicios(string fechaInicio, string fechaFin, string submitButton)
        {
            try
            {
                DateTime fechaI = new DateTime();
                DateTime fechaF = new DateTime();

                if (fechaInicio == "")
                {
                    fechaI = DateTime.MinValue;
                }
                else
                {
                    fechaI = DateTime.Parse(fechaInicio);
                }

                if (fechaFin == "")
                {
                    fechaF = DateTime.MaxValue;
                }
                else
                {
                    fechaF = DateTime.Parse(fechaFin);
                }

                List <Incidencia> incidencias    = fachada.GetIncidenciasReporte(EstadoIncidencia.Finalizada, fechaI, fechaF);
                List <Servicio>   listaServicios = new List <Servicio>();

                foreach (Incidencia i in incidencias)
                {
                    List <Servicio> servicios = fachada.GetServiciosIncidencia(i.Id);
                    if (servicios.Count() != 0)
                    {
                        if (servicios.Count() != 0)
                        {
                            listaServicios.AddRange(servicios);
                        }
                    }
                }

                if (submitButton == "Filtrar")
                {
                    ViewBag.FechaInicio = fechaInicio;
                    ViewBag.FechaFin    = fechaFin;
                    return(View(listaServicios));
                }
                else if (submitButton == "Exportar")
                {
                    if (listaServicios.Count > 0)
                    {
                        DataTable table = new DataTable();
                        table.Columns.Add("Tipo", typeof(string));
                        table.Columns.Add("Vehículo", typeof(string));
                        table.Columns.Add("Taller", typeof(string));
                        table.Columns.Add("Fecha Entrada", typeof(string));
                        table.Columns.Add("Fecha Salida", typeof(string));
                        table.Columns.Add("Estado", typeof(string));
                        table.Columns.Add("Descripción", typeof(string));
                        table.Columns.Add("Número de orden", typeof(string));

                        // Add Three rows with those columns filled in the DataTable.
                        foreach (Servicio s in listaServicios)
                        {
                            table.Rows.Add(s.Tipo, s.Vehiculo.Matricula, s.Taller.Nombre, s.FechaEntrada, s.FechaSalida, s.Estado, s.Descripcion, s.NumeroOrden);
                        }


                        ClosedXML.Excel.XLWorkbook wbook = new ClosedXML.Excel.XLWorkbook();
                        wbook.Worksheets.Add(table, "tab1");
                        // Prepare the response
                        HttpResponseBase httpResponse = Response;
                        httpResponse.Clear();
                        httpResponse.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
                        //Provide you file name here
                        httpResponse.AddHeader("content-disposition", "attachment;filename="Reporte Servicios.xlsx"");

                        // Flush the workbook to the Response.OutputStream
                        using (MemoryStream memoryStream = new MemoryStream())
                        {
                            wbook.SaveAs(memoryStream);
                            memoryStream.WriteTo(httpResponse.OutputStream);
                            memoryStream.Close();
                        }

                        httpResponse.End();
                        return(View(listaServicios));
                    }
                    else
                    {
                        throw new MyException("No hay servicios para exportar en el período");
                    }
                }

                return(View(listaServicios));
            }


            catch (Exception ex)
            {
                throw ex;
            }
        }

        private string ExportToExcel()
        {
            string outputPath = Path.Combine(Context.Config.GetDirectory("Upload"), "MemberReport");
            string excelFile  = Path.Combine(outputPath, "VipDailyJoinList.xlsx");

            FileInfo xlsFile = new FileInfo(excelFile);

            if (xlsFile.Exists)
            {
                xlsFile.Delete();
                xlsFile = new FileInfo(excelFile);
            }

            var wb        = new ClosedXML.Excel.XLWorkbook();
            var worksheet = wb.Worksheets.Add("Sheet1");

            // Set width of columns
            worksheet.Column(1).Width = 13d;
            worksheet.Column(2).Width = 15d;
            worksheet.Column(3).Width = 18d;
            worksheet.Column(4).Width = 18d;
            worksheet.Column(5).Width = 12d;
            worksheet.Column(6).Width = 12d;
            worksheet.Column(7).Width = 12d;
            worksheet.Column(8).Width = 12d;
            worksheet.Column(9).Width = 12d;
            // Setting first row
            // Title
            worksheet.Cell(1, 1).Value = "VIP2800 - VIP Daily Join In Report (Excel)";
            // Report Criteria
            worksheet.Cell(2, 1).Value = "DATE RANGE:";
            worksheet.Cell(2, 2).Value = dtpFromRegDate.Value.ToString(DateTimeHelper.GetDateFormat()) + " TO " + dtpToRegDate.Value.ToString(DateTimeHelper.GetDateFormat());
            worksheet.Cell(3, 1).Value = "PRINTED ON:";
            worksheet.Cell(3, 2).Value = DateTime.Now.ToString(DateTimeHelper.GetDateFormat());
            // Header
            worksheet.Cell(5, 1).Value = "REGISTRATION DATE";
            worksheet.Cell(5, 2).Value = "VIP#";
            worksheet.Cell(5, 3).Value = "NAME";
            worksheet.Cell(5, 4).Value = "EMAIL";
            worksheet.Cell(5, 5).Value = "TEL. WORK";
            worksheet.Cell(5, 6).Value = "TEL. HOME";
            worksheet.Cell(5, 7).Value = "PAGER";
            worksheet.Cell(5, 8).Value = "FAX";
            worksheet.Cell(5, 9).Value = "OTHER";

            // writing data
            DataTable oTable        = DataSource();
            var       rangeWithData = worksheet.Cell(7, 1).InsertData(oTable.AsEnumerable());


            // add some document properties to the spreadsheet

            // set some core property values
            wb.Properties.Title    = "VIP2800 - VIP Daily Join In Report (Excel)";
            wb.Properties.Author   = "RT2020";
            wb.Properties.Subject  = "VIP2800 - VIP Daily Join In Report (Excel)";
            wb.Properties.Keywords = "RT2020";
            wb.Properties.Category = "VIP2800 - VIP Daily Join In Report (Excel)";
            wb.Properties.Comments = "VIP2800 - VIP Daily Join In Report (Excel)";

            // set some extended property values
            wb.Properties.Company = "Synergy";

            // save our new workbook and we are done!
            wb.SaveAs(excelFile);

            return(excelFile);
        }

        //---------------------------------------------------------/
        //      Method
        //---------------------------------------------------------/
        public void ExcelFile()
        {
            string tempFile = Folder.DefaultLocation() + @".~temp.xlsx";

            Cursor.Current = Cursors.WaitCursor;                // マウスカーソルを砂時計(Wait)

            try
            {
                using (oWBook = new XLWorkbook(fileName))
                {
                    if (tncA == null || tncA.Length == 0)
                    {
                        DMessage.DataNotExistence("中断します!");
                        return;
                    }

                    // 編集
                    oWSheet = oWBook.Worksheet(1);        // シートを開く
                    readyExcelRows(tncA.Length, 4);
                    int sNo = 5;
                    for (int i = 0; i < tncA.Length; i++)
                    {
                        using (IXLRange SetRange = oWSheet.Range("A5:M5"))
                            // テンプレートデータ行コピー/ペースト
                            SetRange.CopyTo(oWSheet.Cell(sNo + i, 1));

                        if (i == 0)
                        {
                            officeName = tncA[i].OfficeName;
                            oWSheet.Cell(2, 3).Value = DateTime.Today;
                            oWSheet.Cell(3, 3).Value = officeName;
                        }

                        oWSheet.Cell(sNo + i, 1).Value  = i + 1;
                        oWSheet.Cell(sNo + i, 2).Value  = tncA[i].TaskCode;
                        oWSheet.Cell(sNo + i, 3).Value  = tncA[i].TaskName;
                        oWSheet.Cell(sNo + i, 4).Value  = tncA[i].VersionNo;
                        oWSheet.Cell(sNo + i, 5).Value  = tncA[i].IssueDate;
                        oWSheet.Cell(sNo + i, 6).Value  = tncA[i].SalesMName;
                        oWSheet.Cell(sNo + i, 7).Value  = tncA[i].SalesMInputDate;
                        oWSheet.Cell(sNo + i, 8).Value  = tncA[i].Approval;
                        oWSheet.Cell(sNo + i, 9).Value  = tncA[i].ApprovalDate;
                        oWSheet.Cell(sNo + i, 10).Value = tncA[i].MakeOrder;
                        oWSheet.Cell(sNo + i, 11).Value = tncA[i].MakeOrderDate;
                        oWSheet.Cell(sNo + i, 12).Value = tncA[i].ConfirmAdm;
                        oWSheet.Cell(sNo + i, 13).Value = tncA[i].ConfirmDate;

                        if (i != 0)
                        {
                            oWSheet.Range(sNo + i, 1, sNo + i, 13).Style.Border.TopBorder = XLBorderStyleValues.Hair;
                        }
                        if (i == tncA.Length - 1)
                        {
                            oWSheet.Range(sNo + i, 1, sNo + i, 13).Style.Border.BottomBorder = XLBorderStyleValues.Thin;
                        }
                        else
                        {
                            oWSheet.Range(sNo + i, 1, sNo + i, 13).Style.Border.BottomBorder = XLBorderStyleValues.Hair;
                        }
                    }
                }

                // 保存
                oWBook.SaveAs(tempFile);                      // Excel保存
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                Cursor.Current = Cursors.Default;               // マウスカーソルを戻す
                return;
            }

            Cursor.Current = Cursors.Default;                        // マウスカーソルを戻す

            System.Diagnostics.Process.Start("Excel.exe", tempFile); // 表示用Excel
            // pdf出力にする場合は、上記 System.DiafnosticsのLineをコメントアウトし、下記DateTime以下のコメントを外す。
            // pdf file 出力
            //DateTime now = DateTime.Now;
            //outputFile = System.IO.Path.GetDirectoryName( tempFile ) + @"業務引継書承認未完了一覧表_" + officeName + "_" + "_" + now.ToString( "yyMMddHHmmss" );
            //PublishExcelToPdf etp = new PublishExcelToPdf();
            //etp.ExcelToPDF( tempFile, outputFile );

            //if( File.Exists( tempFile ) ) File.Delete( tempFile );
        }

        private void btnCreateSenior_Click(object sender, EventArgs e)
        {
            var wb = new cXML.XLWorkbook();
            var ws = wb.Worksheets.Add("Members");

            string title = "Senior Report";

            //Title
            ws.Cell("B2").Value = title;

            // Headers
            ws.Cell("B3").Value = "State";
            ws.Cell("C3").Value = "FName";
            ws.Cell("D3").Value = "LName";
            ws.Cell("E3").Value = "Email";

            int skipped = 0;
            int total   = 0;

            // Populate the spreadsheet.
            foreach (string item in cmbReportState.Items)
            {
                skipped = 0;
                for (int i = 4; i - 4 < students.GetLength(0); i++)
                {
                    if (students[i - 4, 0] == null)
                    {
                        break;
                    }
                    if (students[i - 4, 7] == "12" && students[i - 4, 11] == item)
                    {
                        ws.Cell("B" + (i + total - skipped).ToString()).Value = students[i - 4, 11]; // State
                        ws.Cell("C" + (i + total - skipped).ToString()).Value = students[i - 4, 1];  // First Names
                        ws.Cell("D" + (i + total - skipped).ToString()).Value = students[i - 4, 2];  // Last Names
                        ws.Cell("E" + (i + total - skipped).ToString()).Value = students[i - 4, 9];  // Emails
                        total++;
                    }
                    else
                    {
                        skipped++;
                    }
                }
            }

            skipped = studentLength - total;

            //From worksheet
            var rngTable = ws.Range("B2:E" + (studentLength + 5 - skipped).ToString());

            rngTable.FirstCell().Style
            .Font.SetBold()
            .Fill.SetBackgroundColor(cXML.XLColor.CornflowerBlue)
            .Alignment.SetHorizontal(cXML.XLAlignmentHorizontalValues.Center);

            rngTable.FirstRow().Merge();

            var rngHeaders = rngTable.Range("A2:D2"); // The address is relative to rngTable (NOT the worksheet)

            rngHeaders.Style.Alignment.Horizontal = cXML.XLAlignmentHorizontalValues.Center;
            rngHeaders.Style.Font.Bold            = true;
            rngHeaders.Style.Font.FontColor       = cXML.XLColor.DarkBlue;
            rngHeaders.Style.Fill.BackgroundColor = cXML.XLColor.Aqua;

            var rngData    = ws.Range("B3:E" + (studentLength + 5 - skipped).ToString());
            var excelTable = rngData.CreateTable();

            excelTable.ShowTotalsRow = true;

            //Add thick borders to the contents of the spreadsheet
            ws.RangeUsed().Style.Border.OutsideBorder = cXML.XLBorderStyleValues.Thick;

            ws.Columns().AdjustToContents();

            wb.SaveAs(Path.Combine(Application.StartupPath, "SeniorReport.xlsx"));

            msgbox msg = new msgbox("Successfully generated senior report in program's local directory.", "Success", 1);

            msg.Show();
        }

        private void btnCreateReport_Click(object sender, EventArgs e)
        {
            var wb = new cXML.XLWorkbook();
            var ws = wb.Worksheets.Add("Members");

            string title = "Citadel Report";

            if (cmbReportState.Text != "All")
            {
                title += " - " + cmbReportState.Text;
            }

            //Title
            ws.Cell("B2").Value = title;

            // Headers
            ws.Cell("B3").Value = "Mem #";
            ws.Cell("C3").Value = "FName";
            ws.Cell("D3").Value = "LName";
            ws.Cell("E3").Value = "Joined";
            ws.Cell("F3").Value = "Grade";
            ws.Cell("G3").Value = "Due";

            int    skipped = 0;
            int    total   = 0;
            int    owing   = 0;
            int    active  = 0;
            Double fees    = 0;
            Double _temp;

            // Populate the spreadsheet.
            for (int i = 4; i - 4 < students.GetLength(0); i++)
            {
                if (students[i - 4, 0] == null)
                {
                    break;
                }
                if ((students[i - 4, 11] == cmbReportState.Text || cmbReportState.Text == "All") && rbAll.Checked || (rbOwing.Checked && students[i - 4, 3] != "$0.00") || (rbPaid.Checked && students[i - 4, 3] == "$0.00"))
                {
                    ws.Cell("B" + (i - skipped).ToString()).Value = students[i - 4, 0]; // Member Numbers
                    ws.Cell("C" + (i - skipped).ToString()).Value = students[i - 4, 1]; // First Names
                    ws.Cell("D" + (i - skipped).ToString()).Value = students[i - 4, 2]; // Last Names
                    ws.Cell("E" + (i - skipped).ToString()).Value = students[i - 4, 4]; // Year Joined
                    ws.Cell("F" + (i - skipped).ToString()).Value = students[i - 4, 7]; // Grade
                    ws.Cell("G" + (i - skipped).ToString()).Value = students[i - 4, 3]; // Amount Due
                    if (students[i - 4, 3] != "$0.00")
                    {
                        owing++;
                    }
                    if (students[i - 4, 5] == "1")
                    {
                        active++;
                    }
                    Double.TryParse(students[i - 4, 3].Trim('$'), out _temp);
                    fees += _temp;
                    total++;
                }
                else
                {
                    skipped++;
                }
            }

            // Members Owing
            ws.Cell("C" + (studentLength + 4 - skipped).ToString()).Value = "Owing:";
            ws.Cell("C" + (studentLength + 4 - skipped).ToString()).Style.Font.SetBold();

            ws.Cell("D" + (studentLength + 4 - skipped).ToString()).Value = owing.ToString() + " of " + total.ToString();
            ws.Cell("D" + (studentLength + 4 - skipped).ToString()).Style.Alignment.Horizontal = cXML.XLAlignmentHorizontalValues.Center;

            // Active Members
            ws.Cell("C" + (studentLength + 5 - skipped).ToString()).Value = "Active:";
            ws.Cell("C" + (studentLength + 5 - skipped).ToString()).Style.Font.SetBold();

            ws.Cell("D" + (studentLength + 5 - skipped).ToString()).Value = active.ToString() + " of " + total.ToString();
            ws.Cell("D" + (studentLength + 5 - skipped).ToString()).Style.Alignment.Horizontal = cXML.XLAlignmentHorizontalValues.Center;

            // Total Fees due
            ws.Cell("F" + (studentLength + 4 - skipped).ToString()).Value = "Total:";
            ws.Cell("F" + (studentLength + 4 - skipped).ToString()).Style.Font.SetBold();

            ws.Cell("G" + (studentLength + 4 - skipped).ToString()).Value = "$" + fees.ToString();
            ws.Cell("G" + (studentLength + 4 - skipped).ToString()).Style.Alignment.Horizontal = cXML.XLAlignmentHorizontalValues.Center;

            //From worksheet
            var rngTable = ws.Range("B2:G" + (studentLength + 5 - skipped).ToString());

            rngTable.FirstCell().Style
            .Font.SetBold()
            .Fill.SetBackgroundColor(cXML.XLColor.CornflowerBlue)
            .Alignment.SetHorizontal(cXML.XLAlignmentHorizontalValues.Center);

            rngTable.FirstRow().Merge();

            var num = rngTable.Range("A1:A" + (studentLength + 2 - skipped).ToString());

            num.Style.Alignment.Horizontal = cXML.XLAlignmentHorizontalValues.Center;

            var due = rngTable.Range("F1:F" + (studentLength + 2 - skipped).ToString());

            due.Style.Alignment.Horizontal = cXML.XLAlignmentHorizontalValues.Center;

            var rngHeaders = rngTable.Range("A2:F2"); // The address is relative to rngTable (NOT the worksheet)

            rngHeaders.Style.Alignment.Horizontal = cXML.XLAlignmentHorizontalValues.Center;
            rngHeaders.Style.Font.Bold            = true;
            rngHeaders.Style.Font.FontColor       = cXML.XLColor.DarkBlue;
            rngHeaders.Style.Fill.BackgroundColor = cXML.XLColor.Aqua;

            var rngData    = ws.Range("B3:G" + (studentLength + 5 - skipped).ToString());
            var excelTable = rngData.CreateTable();

            excelTable.ShowTotalsRow = true;

            //Add thick borders to the contents of the spreadsheet
            ws.RangeUsed().Style.Border.OutsideBorder = cXML.XLBorderStyleValues.Thick;

            ws.Columns().AdjustToContents();

            wb.SaveAs(Path.Combine(Application.StartupPath, "Report" + reportSuffix() + ".xlsx"));

            msgbox msg = new msgbox("Successfully generated report in program's local directory.", "Success", 1);

            msg.Show();
        }
        //---------------------------------------------------------/
        //      Method
        //---------------------------------------------------------/
        public void ExcelFile(string proc)
        {
            string tempFile = Folder.DefaultLocation() + @".~temp.xlsx";

            Cursor.Current = Cursors.WaitCursor;                // マウスカーソルを砂時計(Wait)

            // Wakamatsu 20170313
            try
            {
                using (oWBook = new XLWorkbook(fileName))
                {
                    // 編集
                    switch (procList.IndexOf(proc))
                    {
                    case 0:
                    case 1:
                        if (pod == null || pod.Length == 0)
                        {
                            DMessage.DataNotExistence("中断します!");
                            return;
                        }
                        //MessageBox.Show("Excel書込み開始");
                        if (proc == payoff)
                        {
                            oWSheet = oWBook.Worksheet(1);          // シートを開く
                            editOsPayOff(pod);                      // 起案書発行
                        }
                        else
                        {
                            // Wakamatsu 20170313
                            //decimal sum = 0M;
                            //int page = pod.Length / posRow;
                            //if (pod.Length % posRow > 0) page++;
                            //for (int i = 0; i < page; i++)
                            //{
                            //    oWSheet = oWBook.Worksheet(i + 1);            // シートを開く
                            //    oWSheet.Cell(3, 5).Value = "'" + (i + 1).ToString() + "/" + page.ToString();
                            //    sum = editOsPayOffS(pod, posRow * i, sum);     // 起案書発行
                            //}
                            oWSheet = oWBook.Worksheet(1);                  // シートを開く
                            oWSheet.Cell(3, 5).Value = "'1/1";
                            editOsPayOffS(pod, posRow, 0);                  // 起案書発行
                            // Wakamatsu 20170313
                        }
                        break;

                    case 2:
                        if (pmd == null || pmd.Length == 0)
                        {
                            DMessage.DataNotExistence("中断します!");
                            return;
                        }
                        //MessageBox.Show("Excel書込み開始");
                        oWSheet = oWBook.Worksheet(1);          // シートを開く
                        editOsPayment(pmd);                     // 調書発行
                        break;

                    default:
                        break;
                    }

                    // 保存
                    oWBook.SaveAs(tempFile);                    // Excel保存
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                Cursor.Current = Cursors.Default;               // マウスカーソルを戻す
                return;
            }
            // Wakamatsu 20170313

            Cursor.Current = Cursors.Default;               // マウスカーソルを戻す
            //System.Diagnostics.Process.Start("Excel.exe", tempFile);                    // 表示用Excel
            // pdf file 出力
            DateTime now = DateTime.Now;

            outputFile = System.IO.Path.GetDirectoryName(tempFile) + @"" + pNameList[procList.IndexOf(proc)] + "_" + itemCode + "_" + now.ToString("yyMMddHHmmss");
            PublishExcelToPdf etp = new PublishExcelToPdf();

            // Wakamatsu 20170313
            //etp.ExcelToPDF(tempFile, outputFile);
            if (etp.ExcelToPDF(tempFile, outputFile) == true)
            {
                if (File.Exists(tempFile))
                {
                    File.Delete(tempFile);
                }
            }
        }
        //作業割り当て表(検査項目詳細版)Excelファイル出力
        public void save_asignlist_by_details_xlsx(List <List <string> > pages, List <string> categories, List <List <object> > data, string filename)
        {
            _write_log __write_log = write_log;

            try
            {
                using (var wb = new ClosedXML.Excel.XLWorkbook())
                {
                    var ws = wb.Worksheets.Add("Sheet1");

                    //ヘッダーセルの処理
                    ws.Rows(1, 1).Height = 111.5;
                    ws.Cell(1, 1).SetValue <string>("PID");
                    //セル結合
                    ws.Range(ws.Cell(1, 1), ws.Cell(2, 1)).Merge(false);
                    ws.Range(ws.Cell(1, 1), ws.Cell(2, 1)).Style.Border.TopBorder    = XLBorderStyleValues.Thin;
                    ws.Range(ws.Cell(1, 1), ws.Cell(2, 1)).Style.Border.BottomBorder = XLBorderStyleValues.Thin;
                    ws.Range(ws.Cell(1, 1), ws.Cell(2, 1)).Style.Border.LeftBorder   = XLBorderStyleValues.Thin;
                    ws.Range(ws.Cell(1, 1), ws.Cell(2, 1)).Style.Border.RightBorder  = XLBorderStyleValues.Thin;
                    ws.Range(ws.Cell(1, 1), ws.Cell(2, 1)).Style.Alignment.SetVertical(XLAlignmentVerticalValues.Top);
                    ws.Range(ws.Cell(1, 1), ws.Cell(2, 1)).Style.Fill.BackgroundColor = XLColor.FromArgb(0xFFFFCC);
                    ws.Range(ws.Cell(1, 1), ws.Cell(2, 1)).Style.Font.FontName        = "MS Pゴシック";

                    ws.Cell(1, 2).SetValue <string>("URL");
                    ws.Cell(1, 2).Style.Border.TopBorder    = XLBorderStyleValues.Thin;
                    ws.Cell(1, 2).Style.Border.BottomBorder = XLBorderStyleValues.Thin;
                    ws.Cell(1, 2).Style.Border.LeftBorder   = XLBorderStyleValues.Thin;
                    ws.Cell(1, 2).Style.Border.RightBorder  = XLBorderStyleValues.Thin;
                    ws.Cell(1, 2).Style.Alignment.SetVertical(XLAlignmentVerticalValues.Top);
                    //セル結合
                    ws.Range(ws.Cell(1, 2), ws.Cell(2, 2)).Merge(false);
                    ws.Range(ws.Cell(1, 2), ws.Cell(2, 2)).Style.Border.TopBorder    = XLBorderStyleValues.Thin;
                    ws.Range(ws.Cell(1, 2), ws.Cell(2, 2)).Style.Border.BottomBorder = XLBorderStyleValues.Thin;
                    ws.Range(ws.Cell(1, 2), ws.Cell(2, 2)).Style.Border.LeftBorder   = XLBorderStyleValues.Thin;
                    ws.Range(ws.Cell(1, 2), ws.Cell(2, 2)).Style.Border.RightBorder  = XLBorderStyleValues.Thin;
                    ws.Range(ws.Cell(1, 2), ws.Cell(2, 2)).Style.Alignment.SetVertical(XLAlignmentVerticalValues.Top);
                    ws.Range(ws.Cell(1, 2), ws.Cell(2, 2)).Style.Fill.BackgroundColor = XLColor.FromArgb(0xFFFFCC);
                    ws.Range(ws.Cell(1, 2), ws.Cell(2, 2)).Style.Font.FontName        = "MS Pゴシック";

                    //列カウンタ
                    int total_cnt = 3;
                    //偶数奇数カウンタ
                    int mod_cnt = 1;

                    //カテゴリのループ
                    for (int hx = 0; hx < categories.Count; hx++)
                    {
                        //結合範囲セル(カテゴリ名のセル)のRangeリスト
                        List <IXLCell> merge_range = new List <IXLCell>();

                        //検査項目のループ
                        for (int cx = 0; cx < data.Count; cx++)
                        {
                            //最初はカテゴリ名を入力
                            if (cx == 0)
                            {
                                //セル結合開始セルRangeを追加
                                merge_range.Add(ws.Column(total_cnt).Cell(1));

                                ws.Cell(1, total_cnt).SetValue <string>(categories[hx]);
                                ws.Cell(1, total_cnt).Style.Alignment.SetVertical(XLAlignmentVerticalValues.Top);
                                ws.Cell(1, total_cnt).Style.Font.FontName         = "MS Pゴシック";
                                ws.Cell(1, total_cnt).Style.Alignment.TopToBottom = true;

                                //カテゴリの順番偶数・奇数で色分け
                                if ((mod_cnt % 2) == 0)
                                {
                                    ws.Cell(1, total_cnt).Style.Fill.BackgroundColor = XLColor.FromArgb(0xCCFF66);
                                }
                                else
                                {
                                    ws.Cell(1, total_cnt).Style.Fill.BackgroundColor = XLColor.FromArgb(0xCCECFF);
                                }
                            }

                            //カテゴリ名の入力セルの下の行に項番とコメント入力
                            var           row = data[cx];
                            string        v0  = (string)row[0];
                            double        v1  = double.Parse((string)row[1]);
                            string        v2  = (string)row[2];
                            string        v3  = "";
                            int           inx = 0;
                            List <string> gs  = (List <string>)row[3];
                            foreach (string tx in gs)
                            {
                                v3 += tx;
                                if (inx != (gs.Count - 1))
                                {
                                    v3 += "rn";
                                }
                                inx++;
                            }

                            //カレントカテゴリと一致する時だけ入力
                            if (v0 == categories[hx])
                            {
                                //数値はValueメソッドで入力
                                ws.Cell(2, total_cnt).Value = v1;
                                ws.Cell(2, total_cnt).Comment.AddText(v2 + v3);
                                ws.Cell(2, total_cnt).Style.Border.TopBorder    = XLBorderStyleValues.Thin;
                                ws.Cell(2, total_cnt).Style.Border.BottomBorder = XLBorderStyleValues.Thin;
                                ws.Cell(2, total_cnt).Style.Border.LeftBorder   = XLBorderStyleValues.Thin;
                                ws.Cell(2, total_cnt).Style.Border.RightBorder  = XLBorderStyleValues.Thin;
                                ws.Cell(2, total_cnt).Style.Alignment.SetHorizontal(XLAlignmentHorizontalValues.Center);
                                ws.Cell(2, total_cnt).Style.Font.FontName = "MS Pゴシック";
                                ws.Column(total_cnt).Width = 4;

                                //カテゴリの順番偶数・奇数で色分け
                                if ((mod_cnt % 2) == 0)
                                {
                                    ws.Cell(2, total_cnt).Style.Fill.BackgroundColor = XLColor.FromArgb(0xCCFF66);
                                }
                                else
                                {
                                    ws.Cell(2, total_cnt).Style.Fill.BackgroundColor = XLColor.FromArgb(0xCCECFF);
                                }
                                total_cnt++;
                            }
                        }

                        //セル結合終了セルRangeを追加
                        merge_range.Add(ws.Column(total_cnt - 1).Cell(1));
                        //セル結合
                        ws.Range(merge_range.First <IXLCell>(), merge_range.Last <IXLCell>()).Merge(false);
                        ws.Range(merge_range.First <IXLCell>(), merge_range.Last <IXLCell>()).Style.Border.TopBorder    = XLBorderStyleValues.Thin;
                        ws.Range(merge_range.First <IXLCell>(), merge_range.Last <IXLCell>()).Style.Border.BottomBorder = XLBorderStyleValues.Thin;
                        ws.Range(merge_range.First <IXLCell>(), merge_range.Last <IXLCell>()).Style.Border.LeftBorder   = XLBorderStyleValues.Thin;
                        ws.Range(merge_range.First <IXLCell>(), merge_range.Last <IXLCell>()).Style.Border.RightBorder  = XLBorderStyleValues.Thin;
                        mod_cnt++;
                    }

                    //データセルの処理
                    //行のループ
                    for (int i = 0; i < pages.Count; i++)
                    {
                        List <string> row = (List <string>)pages[i];

                        //列のループ
                        for (int j = 0; j < row.Count; j++)
                        {
                            string col = (string)row[j];
                            ws.Cell(i + 3, j + 1).SetValue <string>(col);
                            ws.Cell(i + 3, j + 1).Style.Border.TopBorder    = XLBorderStyleValues.Thin;
                            ws.Cell(i + 3, j + 1).Style.Border.BottomBorder = XLBorderStyleValues.Thin;
                            ws.Cell(i + 3, j + 1).Style.Border.LeftBorder   = XLBorderStyleValues.Thin;
                            ws.Cell(i + 3, j + 1).Style.Border.RightBorder  = XLBorderStyleValues.Thin;
                            ws.Cell(i + 3, j + 1).Style.Font.FontName       = "MS Pゴシック";
                            ws.Cell(i + 3, j + 1).Style.Alignment.SetVertical(XLAlignmentVerticalValues.Top);
                        }
                    }

                    //残りのセルの罫線処理
                    for (int i = 0; i < pages.Count; i++)
                    {
                        for (int z = 3; z < total_cnt; z++)
                        {
                            ws.Cell(i + 3, z).Style.Border.TopBorder    = XLBorderStyleValues.Thin;
                            ws.Cell(i + 3, z).Style.Border.BottomBorder = XLBorderStyleValues.Thin;
                            ws.Cell(i + 3, z).Style.Border.LeftBorder   = XLBorderStyleValues.Thin;
                            ws.Cell(i + 3, z).Style.Border.RightBorder  = XLBorderStyleValues.Thin;
                            ws.Cell(i + 3, z).Style.Alignment.SetHorizontal(XLAlignmentHorizontalValues.Center);
                            ws.Cell(i + 3, z).Style.Font.FontName = "MS Pゴシック";
                        }
                    }

                    wb.SaveAs(filename);
                    main_form.Invoke(__write_log, "保存に成功しました。(" + filename + ")");
                }
            }
            catch (Exception ex)
            {
                main_form.Invoke(__write_log, "【エラー】" + ex.Message);
                return;
            }
        }
        /// <summary>
        /// Scrive un datatable su Excel
        /// </summary>
        /// <param name="dt"></param>
        /// <param name="nomeStat"></param>
        /// <param name="titolo"></param>
        /// <param name="sheetName"></param>
        /// <param name="args"></param>
        /// <returns></returns>
        public static ExcelRender EseguiRenderDataTableExcel(DataTable dt, string nomeStat, string titolo, string sheetName, Dictionary <string, string> args)
        {
            var oEsitoRender = new ExcelRender();

            oEsitoRender.NomeFile = String.Format("Report_{0}_{1:yyyyMMdd_HHmmss}.xlsx", nomeStat, DateTime.Now);

            var workbook = new ClosedXML.Excel.XLWorkbook();

            //Se fornito imposta un nome sheet
            if (string.IsNullOrEmpty(sheetName))
            {
                sheetName = nomeStat;
            }

            //Crea sheet dati
            var worksheet = workbook.Worksheets.Add(dt, sheetName);



            worksheet.Rows().AdjustToContents();
            worksheet.Columns().AdjustToContents();

            for (int i = 0; i < dt.Columns.Count - 1; i++)
            {
                var colIdx = i + 1;

                if (dt.Columns[i].DataType == typeof(decimal))
                {
                    worksheet.Column(colIdx).Cells().Style.Alignment.SetHorizontal(XLAlignmentHorizontalValues.Right);
                    worksheet.Column(colIdx).CellsUsed().Style.NumberFormat.Format = "0.00 €";
                }
                else
                {
                    worksheet.Column(colIdx).Cells().Style.Alignment.SetHorizontal(XLAlignmentHorizontalValues.Left);
                }
            }

            //Titolo
            if (!String.IsNullOrEmpty(titolo))
            {
                //Add titolo
                worksheet.FirstRowUsed().InsertRowsAbove(1);

                //Ultima colonna
                var cellLast = worksheet.Cell(1, dt.Columns.Count);

                //Crea range e merge
                var oRange = worksheet.Range("A1:" + cellLast.Address.ColumnLetter + "1").Merge();
                oRange.Value                      = titolo;
                oRange.Style.Font.Bold            = true;
                oRange.Style.Font.FontColor       = ClosedXML.Excel.XLColor.CornflowerBlue;
                oRange.Style.Font.FontSize        = 16d;
                oRange.Style.Fill.BackgroundColor = ClosedXML.Excel.XLColor.Yellow;
                oRange.Style.Alignment.SetHorizontal(XLAlignmentHorizontalValues.Center);
            }

            //Parametri
            if (args != null && args.Count > 0)
            {
                //Crea sheet parametri
                var worksheetp = workbook.Worksheets.Add("Parametri");

                worksheetp.Column(1).Cell(1).Value = "Nome";
                worksheetp.Column(2).Cell(2).Value = "Valore";

                var iRow = 1;
                foreach (var oParam in args)
                {
                    worksheetp.Column(1).Cell(iRow).Value = oParam.Key;
                    worksheetp.Column(2).Cell(iRow).Value = oParam.Value;
                    iRow += 1;
                }
                worksheetp.Rows().AdjustToContents();
                worksheetp.Columns().AdjustToContents();
                worksheetp.Rows(1, 1).Style.Font.Bold = true;
            }

            //Scrive
            var memoryStream = new MemoryStream();

            workbook.SaveAs(memoryStream);
            oEsitoRender.DatiMemory = memoryStream.ToArray();


            return(oEsitoRender);
        }
        public JsonResult ExportExcel(
            DateTime?dateStart, DateTime?dateFinish,
            string start       = "0", string finish = "z",
            string productKind = "",
            string orderby     = "TotalQty", string sort = "desc", int page = 1)
        {
            ResultModel result = new ResultModel();

            //建立Excel
            string template =
                System.Web.Hosting.HostingEnvironment.MapPath("~/Templates/產品銷售排行統計表.xlsx");

            var exportFileName = $"{ Guid.NewGuid().ToString()}.xlsx";
            var fullPath       = Path.Combine(Server.MapPath("~/Temp"), exportFileName);

            XLWorkbook workbook = new ClosedXML.Excel.XLWorkbook(template);

            int rowIndex        = 7;
            int rowIndexForCopy = 7;
            int columnIndex     = 1;
            int rank            = 0;

            try
            {
                var infos = GeQuery(dateStart, dateFinish, start, finish, productKind, orderby, sort);
                var sheet = workbook.Worksheets.First();

                sheet.Cell(2, 2).Value = GetOrderByText(orderby);             //排列方式
                sheet.Cell(3, 2).Value = GetDateRange(dateStart, dateFinish); //銷售日期
                sheet.Cell(4, 2).Value = GetProductKind(productKind);         //產品類別
                sheet.Cell(5, 2).Value = GetProductRange(start, finish);      //產品編號

                foreach (var item in infos)
                {
                    sheet.Cell(rowIndex, columnIndex++).Value = ++rank;
                    sheet.Cell(rowIndex, columnIndex++).Value = $"'{ item.ProductID}";
                    sheet.Cell(rowIndex, columnIndex++).Value = item.ProductName;
                    sheet.Cell(rowIndex, columnIndex++).Value = item.TotalQty;
                    sheet.Cell(rowIndex, columnIndex++).Value = item.TotalAmount;
                    sheet.Cell(rowIndex, columnIndex++).Value = item.TotalProfit;
                    sheet.Cell(rowIndex, columnIndex++).Value = item.GrossProfitMargin;

                    rowIndex++;
                    columnIndex = 1;
                    sheet.Row(rowIndexForCopy).CopyTo(sheet.Row(rowIndex));
                }

                sheet.Row(rowIndex).Delete();

                workbook.SaveAs(fullPath);

                result.Status      = true;
                result.CloseWindow = false;
                result.Url         = exportFileName;
                result.Message     = "MessageComplete".ToLocalized();
            }
            catch (Exception ex)
            {
                result.Status  = false;
                result.Message = ex.Message.ToString();
            }
            return(Json(result));
        }
        public static void exportToExcel(DataTable table, string tableName, string workSheetName, string fileName)
        {
            // Create the excel file and add worksheet
            XLWorkbook workBook = new XLWorkbook();
            IXLWorksheet workSheet = workBook.Worksheets.Add(workSheetName);

            // Hardcode title and contents locations
            IXLCell titleCell = workSheet.Cell(2, 2);
            IXLCell contentsCell = workSheet.Cell(3, 2);

            //Pretty-up the title
            titleCell.Value = tableName;
            titleCell.Style.Font.Bold = true;
            titleCell.Style.Fill.BackgroundColor = XLColor.CornflowerBlue;
            titleCell.Style.Alignment.Horizontal = XLAlignmentHorizontalValues.Center;

            // Merge cells for title
            workSheet.Range(titleCell, workSheet.Cell(2, table.Columns.Count + 1)).Merge();

            // Insert table contents, and adjust for content width
            contentsCell.InsertTable(table);
            workSheet.Columns().AdjustToContents(1, 75);

            // Create a new response and flush it to a memory stream
            System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
            response.Clear();
            response.AddHeader("Content-Disposition", "attachment; filename=" + fileName + ".xlsx;");
            using (MemoryStream stream = new MemoryStream())
            {
                workBook.SaveAs(stream);
                stream.WriteTo(response.OutputStream);
                stream.Close();
            }
            response.End();
        }
        // Public
        public void Create(String filePath)
        {
            var workbook = new XLWorkbook();
            var ws = workbook.Worksheets.Add("Defining a Range");

            // With a string
            var range1 = ws.Range("A1:B1");
            range1.Cell(1, 1).Value = "ws.Range("A1:B1").Merge()";
            range1.Merge();

            // With two XLAddresses
            var range2 = ws.Range(ws.Cell(2, 1).Address, ws.Cell(2, 2).Address);
            range2.Cell(1, 1).Value = "ws.Range(ws.Cell(2, 1).Address, ws.Cell(2, 2).Address).Merge()";
            range2.Merge();

            // With two strings
            var range4 = ws.Range("A3", "B3");
            range4.Cell(1, 1).Value = "ws.Range("A3", "B3").Merge()";
            range4.Merge();

            // With 4 points
            var range5 = ws.Range(4, 1, 4, 2);
            range5.Cell(1, 1).Value = "ws.Range(4, 1, 4, 2).Merge()";
            range5.Merge();

            ws.Column("A").AdjustToContents();

            workbook.SaveAs(filePath);
        }
        // Public
        public void Create(String filePath)
        {
            var wb = new XLWorkbook();
            var ws = wb.Worksheets.Add("Outline");

            ws.Outline.SummaryHLocation = XLOutlineSummaryHLocation.Right;
            ws.Columns(2, 6).Group(); // Create an outline (level 1) for columns 2-6
            ws.Columns(2, 4).Group(); // Create an outline (level 2) for columns 2-4
            ws.Column(2).Ungroup(true); // Remove column 2 from all outlines

            ws.Outline.SummaryVLocation = XLOutlineSummaryVLocation.Bottom;
            ws.Rows(1, 5).Group(); // Create an outline (level 1) for rows 1-5
            ws.Rows(1, 4).Group(); // Create an outline (level 2) for rows 1-4
            ws.Rows(1, 4).Collapse(); // Collapse rows 1-4
            ws.Rows(1, 2).Group(); // Create an outline (level 3) for rows 1-2
            ws.Rows(1, 2).Ungroup(); // Ungroup rows 1-2 from their last outline

            // You can also Collapse/Expand specific outline levels
            //
            // ws.CollapseRows(Int32 outlineLevel)
            // ws.CollapseColumns(Int32 outlineLevel)
            //
            // ws.ExpandRows(Int32 outlineLevel)
            // ws.ExpandColumns(Int32 outlineLevel)

            // And you can also Collapse/Expand ALL outline levels in one shot
            //
            // ws.CollapseRows()
            // ws.CollapseColumns()
            //
            // ws.ExpandRows()
            // ws.ExpandColumns()

            wb.SaveAs(filePath);
        }
        private static void CreateExcelFile(ChromeDriver driver)
        {
            var homeTeams = driver.FindElements(By.ClassName("team-home"));
            var awayTeams = driver.FindElements(By.ClassName("team-away"));
            var scores = driver.FindElements(By.ClassName("score"));

            var wb = new XLWorkbook();
            var ws = wb.Worksheets.Add("Scores");

            ws.Cell("A1").Value = "Home Team";
            ws.Cell("B1").Value = "Score";
            ws.Cell("C1").Value = "Away Team";

            for (int i = 0; i < homeTeams.Count; i++)
            {
                string homeTeam = homeTeams[i].Text;
                string score = scores[i].Text;
                string awayTeam = awayTeams[i].Text;

                ws.Cell("A" + (i + 2)).Value = homeTeam;
                ws.Cell("B" + (i + 2)).Value = score;
                ws.Cell("C" + (i + 2)).Value = awayTeam;
            }

            // Beautify
            ws.Range("A1:C1").Style.Font.Bold = true;
            ws.Columns().AdjustToContents();

            wb.SaveAs("../../../../FlashScore.xlsx");
        }

Понравилась статья? Поделить с друзьями:
  • Closedxml c excel пример
  • Closed word class words
  • Closed form compound word
  • Closed class word classes
  • Close word with vba