Вывод в excel visual studio

9 / 9 / 1

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

Сообщений: 192

1

09.01.2011, 12:25. Показов 79873. Ответов 21


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

Товарищи, приветствую, практически закончил один из своих первых не комерческих, но достаточно ответственных проектов. Но встал, что называется, на предпоследней ступени — это реализация отправки содержимого ричтекстбокса (а туда выводятся сугубо сублимированные данные, типа резултьты расчетов формул, которые собственно фискируются у меня в разных текстбоксах.) в эксель.

Видел ряд обсуждений на эту тему в формуе, однако возникли следующего рода вопросы:

Мне нужно чтобы при нажатии на кнопку, запускалась обработка следующей процедуры.

0. Создавался новый файл эксель с определенными полями

1. Как сделать так, чтобы в определенные ячейки с названиями, я закатал нужную инфу.

2. Реализовать заполнение поля дата/тайм, чтобы при открытии файла было видно когда была выполнена обработка.

3. Сохранение файла в определенной папке.

Процедура должна создавать каждый раз новый файл. Тоесть пункт 0 обязательно должен выполняться по новой.
Это нужно для той цели чтобы этот файл потом можно было отправлять по имайл.

Очень жду советов корифеев.

Заранее благодарен.



0



Programming

Эксперт

94731 / 64177 / 26122

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

Сообщений: 116,782

09.01.2011, 12:25

21

Unril

821 / 712 / 110

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

Сообщений: 825

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

09.01.2011, 14:53

2

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

Решение

Добавляем сборку Microsoft.Office.Interop.Excel.dll.

C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
using System;
using System.Diagnostics;
using System.IO;
using System.Runtime.InteropServices;
using System.Windows.Forms;
 
using Microsoft.Office.Interop.Excel;
 
using Application = Microsoft.Office.Interop.Excel.Application;
 
namespace WindowsFormsApplicationTest2 {
    public partial class MainForm : Form {
        private Application application;
        private Workbook workBook;
        private Worksheet worksheet;
 
        public MainForm() {
            InitializeComponent();
        }
 
        // Передаём данные в Excel
        private void buttonToExcel_Click( object sender, EventArgs e ) {
            // Открываем приложение
            application = new Application {
                DisplayAlerts = false
            };
 
            // Файл шаблона
            const string template = "template.xlsm";
 
            // Открываем книгу
            workBook = application.Workbooks.Open( Path.Combine( Environment.CurrentDirectory, template ) );
 
            // Получаем активную таблицу
            worksheet = workBook.ActiveSheet as Worksheet;
 
            // Записываем данные
            worksheet.Range[ "A2" ].Value = DateTime.Now;
            worksheet.Range[ "A4" ].Value = textData1.Text;
            worksheet.Range[ "A6" ].Value = textData2.Text;
            for ( int i = 0; i < checkedListData3.Items.Count; i++ ) {
                worksheet.Cells[ i + 8, 1 ].Value = checkedListData3.Items[ i ];
                worksheet.Cells[ i + 8, 2 ].Value = checkedListData3.GetItemChecked( i ) ? "Checked" : "Unchecked";
            }
 
            // Показываем приложение
            application.Visible = true;
            TopMost = true;
 
            buttonCloseExcel.Enabled = true;
        }
 
        private void buttonCloseExcel_Click( object sender, EventArgs e ) {
            // Сохраняем и закрываем 
            string savedFileName = "book1.xlsm";
            workBook.SaveAs( Path.Combine( Environment.CurrentDirectory, savedFileName ) );
            CloseExcel();
        }
 
        private void CloseExcel() {
            if ( application != null ) {
                int excelProcessId = -1;
                GetWindowThreadProcessId( application.Hwnd, ref excelProcessId );
 
                Marshal.ReleaseComObject( worksheet );
                workBook.Close();
                Marshal.ReleaseComObject( workBook );
                application.Quit();
                Marshal.ReleaseComObject( application );
 
                application = null;
                // Прибиваем висящий процесс
                try {
                    Process process = Process.GetProcessById( excelProcessId );
                    process.Kill();
                }
                finally {}
            }
        }
 
        [DllImport( "user32.dll", SetLastError = true )]
        static extern uint GetWindowThreadProcessId( int hWnd, ref int lpdwProcessId );
 
        private void MainForm_FormClosed( object sender, FormClosedEventArgs e ) {
            CloseExcel();
        }
    }
}

Автоматизация Microsoft Excel в Microsoft Visual C# .NET
WindowsFormsApplicationTest2.zip



8



9 / 9 / 1

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

Сообщений: 192

10.01.2011, 01:34

 [ТС]

3

Елыыыы зеленые Unril, спасибо за подробнейший ответ. Все по полочкам.

Благодарствую.

Буду колдовать дальше!!!!

Добавлено через 2 часа 39 минут
Черт побъери так и думал что столкнусь с стандартной проблемой

The type or namespace name ‘Office’ does not exist in the namespace ‘Microsoft’ (are you missing an assembly reference?) C:UsersАдминистраторDocumentsVisual Studio 2008ProjectsexceltryexceltryForm1.cs



0



25 / 14 / 3

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

Сообщений: 69

10.01.2011, 17:53

5

Есть неплохой класс для создания файлов эксель, добавления в ячейки текста , картинок, слияния ячеек и тд. Я пробовал — удобно



5



9 / 9 / 1

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

Сообщений: 192

10.01.2011, 21:32

 [ТС]

6

Ну вот именно это я и делал. Ссылка была подключена, в окне референсис, она фигурировала.

Однако при попытке запустить приложение, она подчеркивала Office и выдавала выше озвученную ошибку.

VS у меня 2008.
MS Officw 2003.



0



Zilberman

9 / 9 / 1

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

Сообщений: 192

12.01.2011, 10:33

 [ТС]

7

Все народ, выручайте, мой мозг потек в сапоги.

Вроде только только разобрался во всем этом колоброде под названием работае с эксель.
Теперь мне назойливо встречается в тех или иных ситуациях вот такая дребедень:

Использован старый формат, либо библиотека имеет неверный тип. (Исключение из HRESULT: 0x80028018 (TYPE_E_INVDATAREAD))
Бракует строку:

C#
1
ObjWorkBook = ObjExcel.Workbooks.Add(System.Reflection.Missing.Value);

Сил моих уже нет.
Я так подозреваю это конфликт версий Excel и .Net сборки которую я цепляю?

Я уже забил на основной проект и сделал примитив типа такого, чтобы в подробностях разобраться.

C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Excel = Microsoft.Office.Interop.Excel;
 
 
namespace excelexperiment
{
    public partial class Form1 : Form
    {
        Microsoft.Office.Interop.Excel.Application ObjExcel = new Microsoft.Office.Interop.Excel.Application();
        Microsoft.Office.Interop.Excel.Workbook ObjWorkBook;
        Microsoft.Office.Interop.Excel.Worksheet ObjWorkSheet;
 
        public Form1()
        {
            InitializeComponent();
        }
 
        private void button1_Click(object sender, EventArgs e)
        {
            ObjWorkBook = ObjExcel.Workbooks.Add(System.Reflection.Missing.Value);
            ObjWorkSheet = (Microsoft.Office.Interop.Excel.Worksheet)ObjWorkBook.Sheets[1];
            ObjWorkSheet.Cells[3, 1] = "Имя";
            ObjWorkSheet.Cells[3, 2] = "Фамилия";
            ObjWorkSheet.Cells[3, 3] = "Пол";
            ObjExcel.Visible = true;
            ObjExcel.UserControl = true;
 
        }
    }
         
 }

Удавалось только открыть файл эксель, но при попытке воткнуть туда листы и книги возникало это дебильное сообщение.
Подскажите пожалуйста.

Версия мс офиса 2003
Версия вижуал студии 2008.



0



Zilberman

9 / 9 / 1

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

Сообщений: 192

17.01.2011, 20:53

 [ТС]

8

Народ помогите плиз на конкретном примерчике.
Я уже описывал ситуацию, но все же освежу.

Мне нужно чтобы по нажатию на кнопочку осуществлялось:
1. Открытие файла tz.xls (там форма технического задания, в которое заполняется то что было расчитанно и введено в программе)
2. Перенос в определенные ячейки готовой таблицы моих данных из проги.

Основной принцип реализации я конечно знаю, единственное что не могу описать обращение к нужным ячейкам.

Вот пример того как я начал а вот как описать далее обращение в этом файле к конкретной ячейке я не знаю.

C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Excel = Microsoft.Office.Interop.Excel;
 
namespace WindowsFormsApplication2
{
    
    public partial class Form1 : Form
    {
       
        
        private Excel.Application excelapp;
        private Excel.Window excelWindow;
        public Form1()
        {
            InitializeComponent();
        }
        
        private void button1_Click(object sender, EventArgs e)
        {
                excelapp = new Excel.Application();
                excelapp.Visible = true;
                excelapp.Workbooks.Open(@"D:tz.xls", Type.Missing, Type.Missing, Type.Missing, Type.Missing,
                Type.Missing, Type.Missing, Type.Missing, Type.Missing,
                Type.Missing, Type.Missing, Type.Missing, Type.Missing,
                Type.Missing, Type.Missing);
                excelapp.Workbooks.Open(@"D:tz.xls",
                Type.Missing, Type.Missing, Type.Missing, Type.Missing,
                Type.Missing, Type.Missing, Type.Missing, Type.Missing,
                Type.Missing, Type.Missing, Type.Missing, Type.Missing,
                Type.Missing, Type.Missing);
                
        }
    }
}

Помогите плиз я уже все вроде перечитал по этой дурной теме.



0



821 / 712 / 110

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

Сообщений: 825

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

17.01.2011, 21:02

9

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

worksheet.Range[ «A6» ].Value = textData2.Text;

Я же писал в примере.



0



Zilberman

9 / 9 / 1

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

Сообщений: 192

18.01.2011, 13:48

 [ТС]

10

Увжаемый Unril, подставляя
такую

C#
1
worksheet.Range[ "A6" ].Value = textData2.Text;

тему после моего кода который я описал выше. он ругается на worksheet.

Я так понимаю мне его в моем конкретном коде где-то декларировать надо, прежде чем описывать его методы и свойства.
Я так понимаю именно с этим у меня проблемы (



0



27 / 24 / 1

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

Сообщений: 144

17.10.2011, 09:21

11

using Excel = Microsoft.Office.Interop.Excel; как эта строка будет выглядеть в Visual C++ подскажите пожалуйста, а то я уже задолбался бороться с конфликтом пространств имен.



0



127 / 127 / 8

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

Сообщений: 237

17.10.2011, 09:31

12

Посмотри в сторону вот этой библиотеки



0



27 / 24 / 1

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

Сообщений: 144

17.10.2011, 09:34

13

Там на С#



0



127 / 127 / 8

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

Сообщений: 237

17.10.2011, 09:36

14

там в папке лежит прога, с помощью которой из нужного тебе excel файла, генерирует код. кототрый нужен чтобы его создать

Добавлено через 54 секунды
конечно на c#
я сам ей уже полгода пользуюсь, генерирует какие хочешь xls файлы

Добавлено через 56 секунд
я долго ее искал



0



27 / 24 / 1

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

Сообщений: 144

17.10.2011, 09:37

15

Братец, мне на С++ надо это перевести)



0



127 / 127 / 8

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

Сообщений: 237

17.10.2011, 09:38

16

к сожалению пример не могу скинуть, т.к. использую в одном проекте ее

Добавлено через 58 секунд
сори, не увидел. Ну тебе тогда в другой раздел, где C++ обсуждают, этот то раздел по C#



0



27 / 24 / 1

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

Сообщений: 144

17.10.2011, 09:44

17

Там не могут ответить на этот вопрос



0



127 / 127 / 8

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

Сообщений: 237

17.10.2011, 09:46

18

поищи что нибудь про то как использовать библиотеки на C# в приложениях на c++! наоборот я точно знаю что можно использовать



0



opi

8 / 8 / 2

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

Сообщений: 69

11.05.2012, 19:00

19

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

C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
private void button2_Click(object sender, EventArgs e)
        {
            saveFileDialog1.Filter = "Лист Excel (*.xls)|*.xls";
            saveFileDialog1.FileName = "";
            saveFileDialog1.Title = "Экспорт в Excel";
            StringBuilder sb = new StringBuilder();
          
            Microsoft.Office.Interop.Excel.Application app = new Microsoft.Office.Interop.Excel.Application();
            System.Threading.Thread.CurrentThread.CurrentCulture = System.Globalization.CultureInfo.CreateSpecificCulture("en-US");
            app.Visible = true;
            Microsoft.Office.Interop.Excel.Workbook wb = app.Workbooks.Add(1);
            Microsoft.Office.Interop.Excel.Worksheet ws = (Microsoft.Office.Interop.Excel.Worksheet)wb.Worksheets[1];
 
            int i = 2;
            int i2 = 3;
            foreach (ListViewItem lvi in listView1.Items)
            {
                i = 2;
                foreach (ListViewItem.ListViewSubItem lvs in lvi.SubItems)
                {
                    ws.Cells[i2, i] = lvs.Text;
                    i++;
                }
                i2++;
            }
        }

Этот код всё копирует, но есть одно но… после экспорта данных в эксель первый SubItem дублируется в конце записей. Бред какой-то если честно. Как от него избавиться?

И еще один вопрос. Я воспользовался этой прогой, которую предоставил galexser. Но где и как в коде, что написан выше, записать форматирование из этой программы. В С# работаю в один из первых разов, поэтому прошу разъяснить по-подробней.



0



unijcoder

2 / 2 / 5

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

Сообщений: 132

27.12.2016, 19:13

20

У меня другая проблема. При экспорте из датагрид открывается файл экзель,где все числа в текстовом формате. Как сделать чтобы были в числовом сразу?
Вот код:

C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
private void ExportToExcel()
         {
             Microsoft.Office.Interop.Excel.Application exApp = new Microsoft.Office.Interop.Excel.Application();
          //   Microsoft.Office.Interop.Excel.Application ObjExcel = new Microsoft.Office.Interop.Excel.Application();
          
             Microsoft.Office.Interop.Excel.Workbook ObjWorkBook;
             Microsoft.Office.Interop.Excel.Worksheet ObjWorkSheet;
             //Книга.
             ObjWorkBook = exApp.Workbooks.Add(System.Reflection.Missing.Value);
             //Таблица.
             ObjWorkSheet = (Microsoft.Office.Interop.Excel.Worksheet)ObjWorkBook.Sheets[1];
             exApp.Workbooks.Add();
             Microsoft.Office.Interop.Excel.Worksheet workSheet = (Microsoft.Office.Interop.Excel.Worksheet)exApp.ActiveSheet;
             workSheet.Cells[1, 1] = "x";
             workSheet.Cells[1, 2] = "Prls";
             workSheet.Cells[1, 3] = "Prlspv";
             workSheet.Cells[1, 4] = "Pvihrls";
             int rowExcel = 2; //начать со второй строки.
             for (int i = 0; i < result_grid.Rows.Count; i++)
             {
                 //заполняем строку
                 workSheet.Cells[rowExcel, "A"] = result_grid.Rows[i].Cells["x"].Value;
                 workSheet.Cells[rowExcel, "B"] = result_grid.Rows[i].Cells["Prls"].Value;
                 workSheet.Cells[rowExcel, "C"] = result_grid.Rows[i].Cells["Prlspv"].Value;
                 workSheet.Cells[rowExcel, "D"] = result_grid.Rows[i].Cells["Pvihrls"].Value;
                 ++rowExcel;
                 
             }
             
             string pathToXmlFile;
                 pathToXmlFile = Environment.CurrentDirectory + "" + "MyFile.xls";
             pathToXmlFile.Replace(',', ' ');
                 workSheet.SaveAs(pathToXmlFile);
                
               // exApp.Quit();
                 exApp.Visible = true;
                 exApp.UserControl = true;
 
         }



0



  1. Export Data to Excel Using C#
  2. Export Data From Array to Excel Using C#
  3. Export Data From DataTable to Excel Using C#
  4. Export Data From JSON to Excel Using C#

Export Data to an Excel File Using C#

This tutorial will teach how to export data to an Excel file in C#.

Export Data to Excel Using C#

Adding a reference to build an Excel file and exporting it is necessary to move on with this project.

Add the Reference Package

For different operations of excel, we’ll add the ExcelMapper package. To do that, follow the below steps:

  • Open Visual Studio, create a Console Application and name it.
  • Right-click on the Solution Explorer panel and select Manage NuGet Packages.
  • Now click on the Browse option, search for ExcelMapper, and install it.

    Add Reference

After adding the package, we’ll write the code of an example program. In the below example, we’ll use random data from students.

Example:

  • To begin, import the following libraries:
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using Ganss.Excel;
    
  • Now create a Student class having name and marks data members.
    public class Student {
      public String name { get; set; }
      public double marks { get; set; }
    }
    
  • Create another class named Program and create the Main() method in that class.
    public class Program {
      public static void Main(string[] args) {
      }
    }
    

  • In the Main() method, we’ll create a List<> type object of the Student class.
    var s = new List<Student> {
    }
    
  • This object will be populated with some random Student data as shown below:
    var s = new List<Student> {
      new Student{name="M.Zeeshan",marks= 94.0 },
      new Student{name="Shani",marks= 84.0 },
      new Student{name="Saada g",marks= 74.0 },
      new Student{name="Haseeba",marks= 34.0 },
    };
    
  • Then, create an ExcelMapper object named maper.
    ExcelMapper maper = new ExcelMapper();
    
  • To save the data we just created, we’ll create a sample file in the required path or directory.
    var newFile = @"D:sample.xlsx";
    
  • Lastly, we’ll save the file using ExcelMapper’s maper.Save() function.
    maper.Save(newFile,s,"ShaniData",true);
    

Complete Source Code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Ganss.Excel;

namespace DatatoExcelbyZeeshan {
 public class Program {
  public static void Main(string[] args) {
    var s = new List<Student> {
      new Student{name="M.Zeeshan",marks= 94.0 },
      new Student{name="Shani",marks= 84.0 },
      new Student{name="Saada g",marks= 74.0 },
      new Student{name="Haseeba",marks= 34.0 },
    };
    ExcelMapper maper = new ExcelMapper();
    var newFile = @"D:sample.xlsx";
    maper.Save(newFile,s,"ShaniData",true);
    Console.ReadKey();
  }
 }
 public class Student {
  public String name { get; set; }
  public double marks { get; set; }
 }
}

You’ll get the following output in the sample.xlsx file:

C# Export Data to Excel - Output

Export Data From Array to Excel Using C#

Let’s have an example to understand it practically.

Add the Reference Package

For different operations of excel, we’ll add the ExcelMapper package. To do that, follow the below steps:

  • First, open Visual Studio, create a Console Application and name it.
  • Right-click on the Solution Explorer panel and select Manage NuGet Packages.
  • Now click on the Browse option, search for Spire.Xls, and install it.

    Add Spire Xls

Example:

  • To begin, import the following libraries:
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using Spire.Xls;
    
  • Now, create a new instance of Workbook and give it the name wb.
    Workbook wb = new Workbook();
    
  • Include a new Worksheet and give it the name ws.
    Worksheet ws = wb.Worksheets.Add("ShaniArray");
    
  • Make a new array and give it the name ProgramSubjectResults, then add some data.
    string[,] ProgramSubjectResults = new string[,]{
      {"Name", "City", "Gpa", "Language"},
      {"Zeeshan", "ISB", "3.7", "Flutter Development"},
      {"Saad Jaan", "RWP", "4.0", "Full Stack"},
      {"Haseeba", "FATA", "3.53", "Andriod Development"}
    };
    

  • To include the array on the Worksheet, begin with the cell.
    ws.InsertArray(ProgramSubjectResults,2,1);
    ws.AllocatedRange.AutoFitColumns();
    
  • Finally, give the array you just created a name and save it as an Excel file.
    wb.SaveToFile(@"D:ArraytoExcel.xlsx", ExcelVersion.Version2016);
    

Complete Source Code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Spire.Xls;

namespace ExportArraytoExcelbyZeeshan {
  class Program {
   static void Main(string[] args) {
    Workbook wb = new Workbook();
    wb.Worksheets.Clear();
    Worksheet ws = wb.Worksheets.Add("ShaniArray");
    string[,] ProgramSubjectResults = new string[,]{
      {"Name", "City", "Gpa", "Language"},
      {"Zeeshan", "ISB", "3.7", "Flutter Development"},
      {"Saad Jaan", "RWP", "4.0", "Full Stack"},
      {"Haseeba", "FATA", "3.53", "Andriod Development"}
        };
    ws.InsertArray(ProgramSubjectResults, 2, 1);
    ws.AllocatedRange.AutoFitColumns();
    wb.SaveToFile(@"D:ArraytoExcel.xlsx", ExcelVersion.Version2016);
    }
  }
}

Output:

C# Export Array to Excel - Output

Export Data From DataTable to Excel Using C#

Let’s see how this can be done using the following example.

Add the Reference Package

For exporting DataTable to Excel, we’ll add the ExcelMapper package. To do that, follow the steps we discussed before.

Example:

  • To begin, import the following libraries:
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.Data;
    using Spire.Xls;
    

  • Now, create a new instance of Workbook and give it the name wb.
    Workbook wb = new Workbook();
    wb.Worksheets.Clear();
    
  • Include a new Worksheet instance and give it the name ws.
    Worksheet ws = wb.Worksheets.Add("DataTableToExcel");
    
  • Construct an object of type DataTable and give it the name dt.
    DataTable dt = new DataTable();
    
  • Add Roll Number, Student Name, and Sections as columns.
    dt.Columns.Add("Roll Number", typeof(String));
    dt.Columns.Add("Student Name", typeof(String));
    dt.Columns.Add("Section", typeof(String));
    
  • Now we need to create an object of the DataRow type and give it the name dtr.
    DataRow dtr = dt.NewRow();
    
  • Insert data into the DataRow column as shown below.
    dtr[0] = "130-Arid-3227";
    dtr[1] = "Muhammad Zeeshan";
    dtr[2] = "Bs(IT)8A";
    dt.Rows.Add(dtr);
    dtr = dt.NewRow();
    dtr[0] = "123-Arid-3156";
    dtr[1] = "Bubby Shah";
    dtr[2] = "Bs(AI)7C";
    dt.Rows.Add(dtr);
    dtr = dt.NewRow();
    
  • Write the DataTable column in the spreadsheet we created.
    ws.InsertDataTable(dt, true, 1, 1, true);
    
  • Finally, give the document a name and save it as an Excel file.
    wb.SaveToFile(@"C:DataTableToExcel.xlsx", ExcelVersion.Version2016);
    

Complete Source Code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
using Spire.Xls;

namespace ExportDataTableToExcelByZeeshan {
  class Program {
   static void Main(string[] args) {
    Workbook wb = new Workbook();
    wb.Worksheets.Clear();
    Worksheet ws = wb.Worksheets.Add("DataTableToExcel");
    DataTable dt = new DataTable();
    dt.Columns.Add("Roll Number", typeof(String));
    dt.Columns.Add("Student Name", typeof(String));
    dt.Columns.Add("Section", typeof(String));
    DataRow dtr = dt.NewRow();
    dtr[0] = "130-Arid-3227";
    dtr[1] = "Muhammad Zeeshan";
    dtr[2] = "Bs(IT)8A";
    dt.Rows.Add(dtr);
    dtr = dt.NewRow();
    dtr[0] = "123-Arid-3156";
    dtr[1] = "Bubby Shah";
    dtr[2] = "Bs(AI)7C";
    dt.Rows.Add(dtr);
    dtr = dt.NewRow();
    ws.InsertDataTable(dt, true, 1, 1, true);
    wb.SaveToFile(@"C:DataTableToExcel.xlsx", ExcelVersion.Version2016);
    }
  }
}

Output:

C# Export DataTable to Excel - Output

Export Data From JSON to Excel Using C#

The example below will help us understand how to export JSON data to Excel using C# practically.

Add the Reference Package

For the Json operations of Excel, we’ll add the GemBox.Spreadsheet and Newtonsoft.Json packages. To do that, follow the below steps:

  • First, open Visual Studio, create a Console Application and name it.
  • Right-click on the Solution Explorer panel and select Manage NuGet Packages.
  • Now click on the Browse option, search for GemBox.Spreadsheet and Newtonsoft.Json and install it.

    Add GemBox

    Add Json

Example:

  • To begin, import the following libraries:
    using System;
    using System.Collections.Generic;
    using GemBox.Spreadsheet;
    using Newtonsoft.Json;
    

  • Before using any other class from the GemBox.Spreadsheet package, it is necessary to initialize the license using the SpreadsheetInfo.SetLicense() function.
    SpreadsheetInfo.SetLicense("FREE-LIMITED-KEY");
    
  • Now, create a JSON file with the name JsonData and fill it with the Students data.
    string JsonData = @"{
      ""0"": {
    	""Name"": ""Muhammad Zeeshan"",
    	""Roll"": ""3227"",
    	""GPA"": 3.11,
    	""Fyp"": ""Garden Guide System""
    	},
      ""1"" : {
    	""Name"": ""Bubby Shah"",
    	""Roll"": ""3265"",
    	""GPA"": 2.9,
    	""Fyp"": ""Football Field Management""
      },
      ""2"" : {
    	""Name"": ""Haseeb-Ur-Rehman"",
    	""Roll"": ""3156"",
    	""GPA"": 3.9,
    	""Fyp"": ""Plants Recognition""
    	}
      }";
    
  • We’ll deserialize the JSON string after defining the JSON file.
    Dictionary<string, Student> shani = JsonConvert.DeserializeObject<Dictionary<string, Student>>(JsonData);
    
  • Create a new worksheet in Excel and name it ws. After that, create the header values for the worksheet.
    ExcelWorksheet ws = wb.Worksheets.Add("ShaniJSON" +"");
    ws.Cells[0, 0].Value = "Student Name";
    ws.Cells[0, 1].Value = "Roll No";
    ws.Cells[0, 2].Value = "GPA";
    ws.Cells[0, 3].Value = "FYP";
    
  • After the worksheet has been created, we’ll write the deserialized data into the worksheet.
    int row = 0;
    foreach (Student user in shani.Values) {
      ws.Cells[++row, 0].Value = user.Fname;
      ws.Cells[row, 1].Value = user.Roll;
      ws.Cells[row, 2].Value = user.Gpa;
      ws.Cells[row, 3].Value = user.Fyp;
    }
    

  • In the last step, we will save the file as an Excel file in the specified directory.
    wb.Save(@"D:JSON TO Excel by Zeeshan.xlsx");
    

Complete Source Code:

using System;
using System.Collections.Generic;
using GemBox.Spreadsheet;
using Newtonsoft.Json;

namespace JsontoExcelByZeeshan {
  class Program {
   static void Main(string[] args) {
    SpreadsheetInfo.SetLicense("FREE-LIMITED-KEY");
    string JsonData = @"{
      ""0"": {
        ""Name"": ""Muhammad Zeeshan"",
        ""Roll"": ""3227"",
        ""GPA"": 3.11,
        ""Fyp"": ""Garden Guide System""
      },
      ""1"" : {
        ""Name"": ""Bubby Shah"",
        ""Roll"": ""3265"",
        ""GPA"": 2.9,
        ""Fyp"": ""Football Field Management""
      },
      ""2"" : {
        ""Name"": ""Haseeb-Ur-Rehman"",
        ""Roll"": ""3156"",
        ""GPA"": 3.9,
        ""Fyp"": ""Plants Recognition""
      }
    }";
    Dictionary<string, Student> shani = JsonConvert.DeserializeObject<Dictionary<string, Student>>(JsonData);
    ExcelFile wb = new ExcelFile();
    ExcelWorksheet ws = wb.Worksheets.Add("ShaniJSON" +"");
      ws.Cells[0, 0].Value = "Student Name";
      ws.Cells[0, 1].Value = "Roll No";
      ws.Cells[0, 2].Value = "GPA";
      ws.Cells[0, 3].Value = "FYP";

    int row = 0;
    foreach (Student user in shani.Values) {
      ws.Cells[++row, 0].Value = user.Fname;
      ws.Cells[row, 1].Value = user.Roll;
      ws.Cells[row, 2].Value = user.Gpa;
      ws.Cells[row, 3].Value = user.Fyp;
    }
    wb.Save(@"D:JSON TO Excel by Zeeshan.xlsx");
      }
    }
    class Student {
      [JsonProperty("Name")]
      public string Fname { get; set; }

      [JsonProperty("Roll")]
      public string Roll { get; set; }

      [JsonProperty("GPA")]
      public float Gpa { get; set; }

      [JsonProperty("Fyp")]
      public string Fyp { get; set; }
  }
}

Output:

C# Export JSON to Excel - Output

Давайте научимся быстро и просто создавать и записывать файлы Excel с помощью visual studio c#. Наше самое простое приложение Windows Forms будет брать из текстбокса текст и заносить его в первую ячейку. Статья написана специально для Сергея =).

Начать необходимо с подключения библиотеки Microsoft.Office.Interop.Excel. Выглядеть это должно так:

Если у вас при открытии обозревателя решений – Ссылки – правая кнопка – Добавить ссылку – Сборки – в списке нет Microsoft.Office.Interop.Excel, то добавьте её через Nuget. Проект – управление пакетами NuGet – в строке поиска Excel:

Теперь создайте новый проект Windows Forms и на форму закиньте текстбокс и кнопку. На кнопки кликните два раза, откроется исходный код. В самом верху допишите следующее:

using Excel = Microsoft.Office.Interop.Excel;

А в методе button1_Click замените так:

private void button1_Click(object sender, EventArgs e)
        {
            string fileName = "D:\temp\test.xls";

            try
            {
                var excel = new Excel.Application();

                var workBooks = excel.Workbooks;
                var workBook = workBooks.Add();
                var workSheet = (Excel.Worksheet)excel.ActiveSheet;

                workSheet.Cells[1, "A"] = textBox1.Text;

                workBook.SaveAs(fileName);
                workBook.Close();
            }
            catch (Exception ex) {
                MessageBox.Show("Ошибка: "+ ex.ToString());
            }

            MessageBox.Show("Файл "+ Path.GetFileName (fileName) + " записан успешно!");

        }

Вот, собственно говоря и все. Текст из текстбокса запишется в ячейку A1. Обратите внимание, что папка temp на диске уже должна существовать.

Дополнение. Прочитать первую ячейку

Это тоже просто:

 string fileName = "D:\temp\test.xls";

Excel.Application xlApp = new Excel.Application();
Excel.Workbook xlWorkbook = xlApp.Workbooks.Open(fileName, 0, true, 5, "", "", true, Excel.XlPlatform.xlWindows, "t", false, false, 0, true, 1, 0);
Excel._Worksheet xlWorksheet = (Excel._Worksheet)xlWorkbook.Sheets[1];
Excel.Range xlRange = xlWorksheet.UsedRange;

string temp = (string)(xlRange.Cells[1, 1] as Excel.Range).Value2;// 1 1 - адрес 1-й ячейки
MessageBox.Show(temp);


Автор этого материала — я — Пахолков Юрий. Я оказываю услуги по написанию программ на языках Java, C++, C# (а также консультирую по ним) и созданию сайтов. Работаю с сайтами на CMS OpenCart, WordPress, ModX и самописными. Кроме этого, работаю напрямую с JavaScript, PHP, CSS, HTML — то есть могу доработать ваш сайт или помочь с веб-программированием. Пишите сюда.

тегизаметки, си шарп, excel

what is DataGridView?
The control provides a powerful and flexible way to display data in a tabular format. You can use the DataGridView control to show read-only views of a small amount of data, or you can scale it to show editable views of very large sets of data. You can extend the DataGridView control in a number of ways to build custom behaviors into your applications.
For example, you can programmatically specify your own sorting algorithms, and you can create your own types of cells. You can easily customize the appearance of the DataGridView control by choosing among several properties. Many types of data stores can be used as a data source, or the DataGridView control can operate with no data source bound to it.
what is Excel?
Excel is a spreadsheet program from Microsoft and a component of its Office product group for business applications. Microsoft Excel enables users to format, organize and calculate data in a spreadsheet by organizing data using software like Excel, data analysts and other users can make information easier to view as data is added or changed.
Excel contains a large number of boxes called cells that are ordered in rows and columns. Data is placed in these cells. Excel is a part of the Microsoft Office and Office 365 suites and is compatible with other applications in the Office suite. The spreadsheet software is available for Windows, macOS, Android, and iOS platforms.
DataGridView to excel c#
in this article, I will explain with an example, how to export DataGridView data to an Excel file using C#.DataGridView cannot be exported directly to an Excel file and hence need to generate a DataTable dt and export the DataTable to an Excel file. The DataTable will be exported to a formatted Excel file using the ClosedXml library which is a wrapper of OpenXml.for this tutorial, I have already created the database and all the data is in datagridview.
Step # 1: Create Visual Studio Project:
Open Visual Studio. I am using Visual Studio 2019.
source code

Click on Create New Project.
Now, Select Windows Form App from Template, and Press Next, Following Window will appear. Write Project Name. I have written exporting datagridview to excel.
Now, Click Next, Following WIndow will appear.

Source Code
Select .Net Core 3.1 from Dropdown Menu. Click on the «Create» Button, Project will be created.
Step # 2: Install Nuget Package DocumentFormat.OpenXml and ClosedXml Libraries
for this, we need a document open XML sdk and closedXMl library. You can download the libraries using the following download locations.https://github.com/ClosedXML/ClosedXML
Step # 3: Design Window Forms and writes code

Source Code
The design form will look like this I have created a windows form and connected that form with the database and all the data is loaded into the windows forms application.
Importing data to datagridview.
You will need to import the following namespaces before starting the code.
Design form
DataGridView
Inside the Form Load event, the DataGridView is populated with records from the table.
DataGridview
Export DataGridView to Excel
Inside the Button Click event handler, first, a DataTable is created with columns same as that of the DataGridView, and a loop is executed over the DataGridView rows and all the data is added to the DataTable.Then a Workbook object is created to which the DataTable is added as Worksheet using the Add method which accepts DataTable and the name of the Sheet as parameters.
Once the DataTable is added as a Worksheet to the Workbook, the formatting is done by first setting the Header row background color and then applying background colors to the rows and the alternating rows of the Excel file.
Finally, the export data to and export data WorkBook is saved to the specified location on the disk. we can use that workbook as a normal excel documents or workbook. we can also create or fill and export large excel files and normal excel sheets and we can set the filename as well to set the name we have to set the name of the project and then save the name of the file as a string.
Before you write source code, you must add a reference to the Microsoft Excel object library. Right-click on your project and select Add Reference menu. After that go to the COM tab and select and add Microsoft Excel 12.0 object library. Now here is my Button click event handler where I create Excel object sender or object obj and documents, get data from DataGridView, and add rows and columns to the document.
Export data source code sample
Code Sample
sample code
Excel files
after writing the complete source code when we press the export data button the excel file will be generate and when we open the excel file we will get a look like this. all the data of database will be in excel file
Excel file
This is the completion of the guide. I hope it was easy for you to follow and understand. So, what are you waiting for? 30 Days Free Trial You can obtain the License here and begin straightaway. If you are not yet an IronPDF customer, you can try 30-day free trial to check out their available features. If you buy the complete Iron Suite, you will get all 5 Products for the Price of 2. For further details about the licensing, please follow this link to Purchase the complete Package.
You can download the software product from this link.

Have you ever hear NPOI, a .NET library that can read/write Office formats without Microsoft Office installed. No COM+, no interop. Github Page

This is my Excel Export class

/*
 * User: TMPCSigit aswzen@gmail.com
 * Date: 25/11/2019
 * Time: 11:28
 * 
 */
using System;
using System.IO;
using System.Text.RegularExpressions;
using System.Windows.Forms;

using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;

namespace Employee_Manager
{
    public static class ExportHelper
    {       
        public static void WriteCell( ISheet sheet, int columnIndex, int rowIndex, string value )
        {
            var row = sheet.GetRow( rowIndex ) ?? sheet.CreateRow( rowIndex );
            var cell = row.GetCell( columnIndex ) ?? row.CreateCell( columnIndex );

            cell.SetCellValue( value );
        }
        public static void WriteCell( ISheet sheet, int columnIndex, int rowIndex, double value )
        {
            var row = sheet.GetRow( rowIndex ) ?? sheet.CreateRow( rowIndex );
            var cell = row.GetCell( columnIndex ) ?? row.CreateCell( columnIndex );

            cell.SetCellValue( value );
        }
        public static void WriteCell( ISheet sheet, int columnIndex, int rowIndex, DateTime value )
        {
            var row = sheet.GetRow( rowIndex ) ?? sheet.CreateRow( rowIndex );
            var cell = row.GetCell( columnIndex ) ?? row.CreateCell( columnIndex );

            cell.SetCellValue( value );
        }
        public static void WriteStyle( ISheet sheet, int columnIndex, int rowIndex, ICellStyle style )
        {
            var row = sheet.GetRow( rowIndex ) ?? sheet.CreateRow( rowIndex );
            var cell = row.GetCell( columnIndex ) ?? row.CreateCell( columnIndex );

            cell.CellStyle = style;
        }

        public static IWorkbook CreateNewBook( string filePath )
        {
            IWorkbook book;
            var extension = Path.GetExtension( filePath );

            // HSSF => Microsoft Excel(xls形式)(excel 97-2003)
            // XSSF => Office Open XML Workbook形式(xlsx形式)(excel 2007以降)
            if( extension == ".xls" ) {
                book = new HSSFWorkbook();
            }
            else if( extension == ".xlsx" ) {
                book = new XSSFWorkbook();
            }
            else {
                throw new ApplicationException( "CreateNewBook: invalid extension" );
            }

            return book;
        }
        public static void createXls(DataGridView dg){
            try {
                string filePath = "";
                SaveFileDialog sfd = new SaveFileDialog();
                sfd.Filter = "Excel XLS (*.xls)|*.xls";
                sfd.FileName = "Export.xls";
                if (sfd.ShowDialog() == DialogResult.OK)
                {
                    filePath = sfd.FileName;
                    var book = CreateNewBook( filePath );
                    book.CreateSheet( "Employee" );
                    var sheet = book.GetSheet( "Employee" );
                    int columnCount = dg.ColumnCount;
                    string columnNames = "";
                    string[] output = new string[dg.RowCount + 1];
                    for (int i = 0; i < columnCount; i++)
                    {
                        WriteCell( sheet, i, 0, SplitCamelCase(dg.Columns[i].Name.ToString()) );
                    }
                    for (int i = 0; i < dg.RowCount; i++)
                    {
                        for (int j = 0; j < columnCount; j++)
                        {
                            var celData =  dg.Rows[i].Cells[j].Value;
                            if(celData == "" || celData == null){
                                celData = "-";
                            }
                            if(celData.ToString() == "System.Drawing.Bitmap"){
                                celData = "Ada";
                            }
                            WriteCell( sheet, j, i+1, celData.ToString() );
                        }
                    }
                    var style = book.CreateCellStyle();
                    style.DataFormat = book.CreateDataFormat().GetFormat( "yyyy/mm/dd" );
                    WriteStyle( sheet, 0, 4, style );
                    using( var fs = new FileStream( filePath, FileMode.Create ) ) {
                        book.Write( fs );
                    }
                }
            }
            catch( Exception ex ) {
                Console.WriteLine( ex );
            }
        }
        public static string SplitCamelCase(string input)
        {
            return Regex.Replace(input, "(?<=[a-z])([A-Z])", " $1", RegexOptions.Compiled);
        }
    }
}

Понравилась статья? Поделить с друзьями:

А вот еще интересные статьи:

  • Вывести все значения по условию в excel
  • Вывод в excel pandas
  • Вывести все значения массива excel
  • Вывод в excel java
  • Вывести все дубликаты excel

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии