I am currently running a C# project, which processes a lot of data and stores it in a SQLite database. However I would like to export these files from the database to a simple excel sheet, for example create some file, where each table in the database is a sheet in excel, just a plain copy.
At the moment I am doing the same thing with a .csv streamwriter and it is very slow because i have an amount of like 140000 datasets. This means it would require to copy the table as a whole or do it blockwise.
I did not find any code snippets how to do this in c# with sqlite. Do you have any ideas, how I could do this?
I never did this in SQLite and i also think output directly is always better, but i'm curious about this.
So i have written this try-out:
using System;
using System.Data.SQLite;
using Excel = Microsoft.Office.Interop.Excel;
namespace ExcelSqlite
{
internal class Program
{
private static void Main(string[] args)
{
Excel.Application xlApp;
Excel.Workbook xlWorkBook;
Excel.Worksheet xlWorkSheet;
object misValue = System.Reflection.Missing.Value;
xlApp = new Excel.Application();
xlWorkBook = xlApp.Workbooks.Add(misValue);
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
string cs = "URI=file:test.db";
string data = String.Empty;
int i = 0;
int j = 0;
using (SQLiteConnection con = new SQLiteConnection(cs))
{
con.Open();
string stm = "SELECT * FROM Contacts";
using (SQLiteCommand cmd = new SQLiteCommand(stm, con))
{
using (SQLiteDataReader rdr = cmd.ExecuteReader())
{
while (rdr.Read()) // Reading Rows
{
for (j = 0; j <= rdr.FieldCount - 1; j++) // Looping throw colums
{
data = rdr.GetValue(j).ToString();
xlWorkSheet.Cells[i + 1, j + 1] = data;
}
i++;
}
}
}
con.Close();
}
xlWorkBook.SaveAs("sqliteToExcel.xls", Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
xlWorkBook.Close(true, misValue, misValue);
xlApp.Quit();
releaseObject(xlWorkSheet);
releaseObject(xlWorkBook);
releaseObject(xlApp);
}
private static void releaseObject(object obj)
{
try
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
obj = null;
}
catch (Exception ex)
{
obj = null;
}
finally
{
GC.Collect();
}
}
}
}
Hope so, this will lead you to the right direction.
Related
I've looked at all the possible answers on stackoverflow and still cant figure out how to solve my problem.
My program creates an excel file, exports data into the file and then should close it. It doesn't close it completely however and the excel process is still running in the background which makes using my code more than once impossible as it always throws up an error.
I start of by creating my excel object
Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();
I then assign variables to everything I need to use:
Excel.Workbook xlWorkBook;
Excel.Worksheet xlWorkSheet;
object misValue = System.Reflection.Missing.Value;
xlWorkBook = xlApp.Workbooks.Add(misValue);
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
then do all my manipulation.
To close the excel process I use:
xlWorkBook.SaveAs(#"C:\Users\dphillips\Desktop\Projects\C#\Exported Excel File", Excel.XlFileFormat.xlWorkbookNormal,
misValue, misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
xlWorkBook.Close(true, "Exported Excel File", misValue);
xlApp.Quit();
Marshal.FinalReleaseComObject(xlWorkSheet);
Marshal.FinalReleaseComObject(xlWorkBook);
Marshal.FinalReleaseComObject(xlApp);
xlWorkSheet = null;
xlApp = null;
xlWorkBook = null;
The process doesn't close though. I used http://csharp.net-informations.com/excel/csharp-create-excel.htm as my template to do this as I'm new to C# and don't have enough experience to do it on my own.
Any advice on how to correctly close the program would be greatly appreciated
EDIT:
Since I can't seem to get any luck with it I will just post my whole program. Maybe then you could tell me exactly where I'm going wrong
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using System.Text.RegularExpressions;
using System.Runtime.InteropServices;
using Excel = Microsoft.Office.Interop.Excel;
namespace FormPractice
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
FolderBrowserDialog FBD = new FolderBrowserDialog();
if (FBD.ShowDialog() == DialogResult.OK)
{
textBox1.Text = FBD.SelectedPath;
//Creating excel object
Excel.Application xlApp = new Excel.Application();
xlApp.Visible = true;
//Check to see that excel is installed.
if (xlApp == null)
{
MessageBox.Show("Excel is not properly installed!!");
return;
}
// regular expressions to check for the ID number in the file and the issue number of the document
Regex regularExpressionDocID = new Regex(#"\d{3}[A-Z]\W\d{4}\W\d{6}\W\d{3}\W[A-Z]\d{2}");
Regex regularExpressionIssueNumber = new Regex(#"[i,I]s+(ue)*.?\d{1,2}$");
var filesToBeRead = Directory.GetFiles(FBD.SelectedPath, "*.*", SearchOption.AllDirectories)
.Where(fileNameBeingProcessed =>
(fileNameBeingProcessed.EndsWith(".txt")
|| fileNameBeingProcessed.EndsWith(".docx")
|| fileNameBeingProcessed.EndsWith(".doc")
|| fileNameBeingProcessed.EndsWith(".xls")
|| fileNameBeingProcessed.EndsWith(".pdf")
|| fileNameBeingProcessed.EndsWith(".docm")
|| fileNameBeingProcessed.EndsWith(".xlsm")
|| fileNameBeingProcessed.EndsWith(".xlsx")))
.ToList();
var xlWorkBooks = xlApp.Workbooks;
object misValue = System.Reflection.Missing.Value;
var xlWorkBook = xlWorkBooks.Add(misValue);
var xlWorkSheets = xlWorkBook.Worksheets;
var xlWorkSheet = (Excel.Worksheet)xlWorkSheets.get_Item(1);
string comparingString;
int counter = 2;
// setting all headers
xlWorkSheet.Cells[1, 1] = "Document Number";
xlWorkSheet.Cells[1, 2] = "Name";
xlWorkSheet.Cells[1, 3] = "System Revision";
xlWorkSheet.Cells[1, 4] = "Revision";
xlWorkSheet.Cells[1, 5] = "Type";
xlWorkSheet.Cells[1, 6] = "Old Name";
xlWorkSheet.Cells[1, 7] = "File Name";
xlWorkSheet.Cells[1, 8] = "Directory";
xlWorkSheet.Cells[1, 9] = "Owner";
foreach (string file in filesToBeRead)
{
string documentID, documentName, revision, oldName, directoryOfFile, stringToBeManipulated;
comparingString = Path.GetFileNameWithoutExtension(file);
Match matchesFormat = regularExpressionDocID.Match(comparingString);
Match matchesIssue = regularExpressionIssueNumber.Match(comparingString);
// All manipulations to get each of the required fields for the ARAS upload xlsx
if (matchesFormat.Success)
{
stringToBeManipulated = (Path.GetFileNameWithoutExtension(file)); // document ID sectiom
documentID = stringToBeManipulated.Substring(0, 24);
xlWorkSheet.Cells[counter, 1] = documentID;
if (matchesIssue.Success)
{
//If "issue" is found then gives name(from char [25] and inserts issue into the correct cells
revision = matchesIssue.Value;
documentName = stringToBeManipulated[25..matchesIssue.Index];
}
else
{
//If "issue" is not found fills the issue column with a "-" and makes the entire string the name.
revision = "-";
documentName = stringToBeManipulated[25..stringToBeManipulated.Length];
}
xlWorkSheet.Cells[counter, 2] = documentName;
xlWorkSheet.Cells[counter, 3] = revision;
xlWorkSheet.Cells[counter, 4] = revision;
oldName = (Path.GetFileName(file));
xlWorkSheet.Cells[counter, 6] = oldName;
xlWorkSheet.Cells[counter, 7] = oldName;
directoryOfFile = Path.GetDirectoryName(file);
xlWorkSheet.Cells[counter, 8] = directoryOfFile;
counter++;
}
}
xlWorkBook.SaveAs(#"C:\Users\dphillips\Desktop\Projects\C#\Exported_Old_Doc_ID", Excel.XlFileFormat.xlWorkbookNormal,
misValue, misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
xlWorkBook.Close(true, "Exported Excel File", misValue);
xlApp.DisplayAlerts = false;
xlApp.Quit();
//Releasing all objects to stop memory leaks
GC.WaitForPendingFinalizers();
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
Marshal.FinalReleaseComObject(xlWorkSheet);
Marshal.FinalReleaseComObject(xlWorkBook);
Marshal.FinalReleaseComObject(xlWorkSheets);
Marshal.FinalReleaseComObject(xlWorkBooks);
Marshal.FinalReleaseComObject(xlApp);
xlWorkSheet = null;
xlApp = null;
xlWorkBook = null;
xlWorkBooks = null;
xlWorkSheets = null;
MessageBox.Show(#"Excel file created , you can find the file C:\Users\dphillips\Desktop\Projects\C#\Directory to pull");
}
GC.Collect();
Close();
I am new in C# Programming. I am creating a winform application in which I am using System.Windows.Forms.DataVisualization Chart. This chart contains multiple series. I want to export that chart data to Excel file.
To Add Data to chart I am using
chart.Series[mSeries].Points.AddXY(dt, avgData);
dt is current DateTime and the data.
So my Excel file look like
First Column is Series Name, second is DateTime and third column contain data.
So, can anyone please tell me how I can do this.
Thanks in Advance
You can refer to the following solution. First you will need to add reference to Microsoft Excel Object Library of COM. See this link on how to add. Then next step is pretty simple. You will need to add the code from the above link and replace the data which you fed in Excel with your custom data.
Here is the code shown in the link.
private void button1_Click(object sender, EventArgs e)
{
Excel.Application xlApp;
Excel.Workbook xlWorkBook;
Excel.Worksheet xlWorkSheet;
object misValue = System.Reflection.Missing.Value;
xlApp = new Excel.Application();
xlWorkBook = xlApp.Workbooks.Add(misValue);
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
for (int i = 0; i < chart1.Series.Count; i++)
{
xlWorkSheet.Cells[1, 1] = "";
xlWorkSheet.Cells[1, 2] = "DateTime";//put your column heading here
xlWorkSheet.Cells[1, 3] = "Data";// put your column heading here
for (int j = 0; j < chart1.Series[i].Points.Count; j++)
{
xlWorkSheet.Cells[j + 2 , 2] = chart1.Series[i].Points[j].XValue;
xlWorkSheet.Cells[j + 2 , 3] = chart1.Series[i].Points[j].YValues[0];
}
}
Excel.Range chartRange;
Excel.ChartObjects xlCharts = (Excel.ChartObjects)xlWorkSheet.ChartObjects(Type.Missing);
Excel.ChartObject myChart = (Excel.ChartObject)xlCharts.Add(10, 80, 300, 250);
Excel.Chart chartPage = myChart.Chart;
chartRange = xlWorkSheet.get_Range("B2", "c5");//update the range here
chartPage.SetSourceData(chartRange, misValue);
chartPage.ChartType = Excel.XlChartType.xlColumnClustered;
xlWorkBook.SaveAs("csharp.net-informations.xls", Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
xlWorkBook.Close(true, misValue, misValue);
xlApp.Quit();
releaseObject(xlWorkSheet);
releaseObject(xlWorkBook);
releaseObject(xlApp);
MessageBox.Show("Excel file created , you can find the file c:\\csharp.net-informations.xls");
}
private void releaseObject(object obj)
{
try
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
obj = null;
}
catch (Exception ex)
{
obj = null;
MessageBox.Show("Exception Occured while releasing object " + ex.ToString());
}
finally
{
GC.Collect();
}
}
Simply replace the cells and data from the code with your custom data and viola when you click on export button it will export it for you.
I'm fairly new with C# and I am trying to export some data from a DataGridView in C# into an Excel file. The inputs from the datagridview are filled in by the user.
Currently, my program can create an excel file along with the values from the datagridview with the given date as its file name.
My problem is I can't seem to find a way to append the data from the gridview IF the excel file already exists, it overwrites the current excel file instead.
Any help/tips/suggestion is highly appreciated.
Thanks :)
Here is my code:
Microsoft.Office.Interop.Excel.Application xlApp;
Microsoft.Office.Interop.Excel.Workbook xlWorkBook;
Microsoft.Office.Interop.Excel.Worksheet xlWorkSheet;
Microsoft.Office.Interop.Excel.Sheets xlBigSheet;
Microsoft.Office.Interop.Excel.Sheets xlSheet;
object misValue;
String newPath;
private void buttonOK_Click(object sender, EventArgs e)
{
createXLSfile();
}
private void createXLSfile(){
String cDate = datePicker.Value.ToShortDateString();
String cMonth = datePicker.Value.ToString("MMMM");
String cYear = datePicker.Value.ToString("yy");
String cDay = datePicker.Value.ToString("dd");
String fName = cDay + "-" + cMonth+ "-" + cYear + ".xls";
String mainPath = #"C:\Users\User1\Desktop\" + cYear;
String folderPath = System.IO.Path.Combine(mainPath, cMonth);
String excelPath = System.IO.Path.Combine(folderPath, fName);
System.IO.Directory.CreateDirectory(mainPath);
System.IO.Directory.CreateDirectory(folderPath);
String fNameOnly = Path.GetFileNameWithoutExtension(excelPath);
String extension = Path.GetExtension(excelPath);
String path = Path.GetDirectoryName(excelPath);
newPath = excelPath;
if(File.Exists(newPath))
{
existingFile();
}else
{
newFile();
}
MessageBox.Show("Submitted");
}
private void newFile()
{
xlApp = new Microsoft.Office.Interop.Excel.Application();
xlApp.Visible = true;
misValue = System.Reflection.Missing.Value;
xlWorkBook = xlApp.Workbooks.Add(misValue);
xlWorkSheet = (Microsoft.Office.Interop.Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
xlWorkSheet = xlWorkBook.Sheets["Sheet1"];
xlWorkSheet = xlWorkBook.ActiveSheet;
xlWorkSheet.Name = "Sheet1";
xlWorkSheet.Cells[2, 1] = "Header1";
xlWorkSheet.Cells[2, 2] = "Header2";
xlWorkSheet.Cells[2, 3] = "Total";
getData();
xlWorkBook.SaveAs(newFullPath, Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookNormal, misValue,
misValue, misValue, misValue, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
xlWorkBook.Close(true, misValue, misValue);
xlApp.Quit();
Marshal.ReleaseComObject(xlWorkSheet);
Marshal.ReleaseComObject(xlWorkBook);
Marshal.ReleaseComObject(xlApp);
}
private void existingFile()
{
xlApp = new Microsoft.Office.Interop.Excel.Application();
xlApp.Visible = true;
xlWorkBook = xlApp.Workbooks.Open(newPath, 0,
false, 5, "", "", false, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows,
"", true, false, 0, true, false, false);
xlBigSheet = xlWorkBook.Worksheets;
string x = "Sheet1";
xlWorkSheet = (Microsoft.Office.Interop.Excel.Worksheet)xlBigSheet.get_Item(x);
getData();
xlWorkBook.SaveAs(newPath, Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookNormal,
misValue, misValue, misValue, misValue, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive,
misValue, misValue, misValue,
misValue, misValue);
xlWorkBook.Close(misValue, misValue, misValue);
xlWorkBook = null;
xlApp.Quit();
GC.WaitForPendingFinalizers();
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
}
private void getData()
{
double a,b,c,d,total = 0;
int lastRow_ = 3;
foreach(DataGridViewRow r in dataGridView1.Rows)
{
if(!r.IsNewRow)
{
a = Convert.ToDouble(r.Cells[2].Value);
b = Convert.ToDouble(r.Cells[3].Value);
c = Convert.ToDouble(r.Cells[4].Value);
d = Convert.ToDouble(r.Cells[5].Value);
total = a + b + c + d;
xlWorkSheet.Cells[lastRow_, 1] = "Hi";
xlWorkSheet.Cells[lastRow_, 2] = "Hello";
xlWorkSheet.Cells[lastRow_, 3] = Convert.ToString(total);
lastRow_ = xlWorkSheet.Cells.Find(
"*",
xlWorkSheet.Cells[1, 1],
misValue,
Microsoft.Office.Interop.Excel.XlLookAt.xlPart,
Microsoft.Office.Interop.Excel.XlSearchOrder.xlByRows,
Microsoft.Office.Interop.Excel.XlSearchDirection.xlPrevious,
misValue,
misValue,
misValue).Row + 1;
}
}
total = 0;
}
Update 1:
Still stuck.
Been trying to follow this link:
https://www.codeproject.com/articles/5123/opening-and-navigating-excel-with-c
OUTPUT
Directory of outputted excel file
This is what's inside the outputted excel file
When you need to append data to an existing worksheet, you need to find out where the last used row is and start adding data after this row. Your current code to get this “last” row is awkward as once you start adding rows you keep checking for this “last” row which is unnecessary. The getData() method is simply adding data to a new excel file where the last row won’t matter. If the file exists, then you simply need to get the last used row and start importing the data on the next row. I am guessing it may be better as your code goes, to send over a starting row index for the GetData(RowToStart) method and simply increment the lastRow_ variable, like below: There is no need to keep checking for this last row.
private void getData(int lastRow_) {
double a, b, c, d, total = 0;
//int lastRow_ = 4;
foreach (DataGridViewRow r in dataGridView1.Rows) {
//if (!row.IsNewRow) {
if (!r.IsNewRow) {
a = Convert.ToDouble(r.Cells[2].Value);
b = Convert.ToDouble(r.Cells[3].Value);
c = Convert.ToDouble(r.Cells[4].Value);
d = Convert.ToDouble(r.Cells[5].Value);
total = a + b + c + d;
xlWorkSheet.Cells[lastRow_, 1] = "Hi";
xlWorkSheet.Cells[lastRow_, 2] = "Hello";
xlWorkSheet.Cells[lastRow_, 3] = Convert.ToString(total);
lastRow_++;
//lastRow_ = xlWorkSheet.Cells.Find(
// "*",
// xlWorkSheet.Cells[1, 1],
// misValue,
// Microsoft.Office.Interop.Excel.XlLookAt.xlPart,
// Microsoft.Office.Interop.Excel.XlSearchOrder.xlByRows,
// Microsoft.Office.Interop.Excel.XlSearchDirection.xlPrevious,
// misValue,
// misValue,
// misValue).Row + 1;
}
}
total = 0;
}
If the file is new, you would call this method like below.
.
.
.
xlWorkSheet.Cells[3, 1] = "Header1";
xlWorkSheet.Cells[3, 2] = "Header2";
xlWorkSheet.Cells[3, 3] = "Total";
getData(4);
.
.
.
If the file already exists and you need to append the data to existing worksheet you need to get the last used row then start on the next row. You can call getData(RowToStart) like below.
.
.
.
xlWorkSheet = (Microsoft.Office.Interop.Excel.Worksheet)xlBigSheet.get_Item("Sheet1");
Microsoft.Office.Interop.Excel.Range last = xlWorkSheet.Cells.SpecialCells(Microsoft.Office.Interop.Excel.XlCellType.xlCellTypeLastCell, Type.Missing);
int lastUsedRow = last.Row;
getData(lastUsedRow + 1);
.
.
.
I hope this makes sense.
How can I export this data table to excel using: "Microsoft.Office.Interop.Excel" I have this code witch grabs all the data form Master table and want to export it to excel for better view, don't want to use datagrid. There are a lot of post regarding this topic I think, but usually just recommend using some ad on like "closedxml"
OleDbConnection mycon;
DataTable Table = new DataTable("AllData");
mycon = new OleDbConnection(#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\jm11321\Documents\DB.mdb;Persist Security Info=False");
string command = "Select *From Master";
OleDbCommand oleDbCmd = new OleDbCommand(command,mycon);
OleDbDataAdapter adapt = new OleDbDataAdapter(oleDbCmd);
mycon.Open();
adapt.Fill(Table);
mycon.Close();
Any help is appreciated.
You have to import Microsoft.Office.Interop.Excel.dll library from here. Add new class file in your project say ExcelUtility. Just write down the following code in it.
using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using Excel = Microsoft.Office.Interop.Excel;
namespace ExcelDemo
{
public class ExcelUtility
{
public static void CreateExcel(DataSet ds, string excelPath)
{
Excel.Application xlApp;
Excel.Workbook xlWorkBook;
Excel.Worksheet xlWorkSheet;
object misValue = System.Reflection.Missing.Value;
try
{
//Previous code was referring to the wrong class, throwing an exception
xlApp = new Excel.Application();
xlWorkBook = xlApp.Workbooks.Add(misValue);
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
for (int i = 0; i <= ds.Tables[0].Rows.Count - 1; i++)
{
for (int j = 0; j <= ds.Tables[0].Columns.Count - 1; j++)
{
xlWorkSheet.Cells[i + 1, j + 1] = ds.Tables[0].Rows[i].ItemArray[j].ToString();
}
}
xlWorkBook.SaveAs(excelPath, Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
xlWorkBook.Close(true, misValue, misValue);
xlApp.Quit();
releaseObject(xlApp);
releaseObject(xlWorkBook);
releaseObject(xlWorkSheet);
}
catch (Exception ex)
{
throw ex;
}
}
private static void releaseObject(object obj)
{
try
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
obj = null;
}
catch
{
obj = null;
}
finally
{
GC.Collect();
}
}
}
}
Now in main code just pass the dataset object and excel path as below.
ExcelUtility.CreateExcel(ds, "D:\\Demo.xls");
I have already tested and using this in my projects.
I know that there is already an answer, although here is another approach
var workbook = new XLWorkbook();
var worksheet = workbook.Worksheets.Add("Sample Sheet");
worksheet.Cell("A1").Value = "Hello World!";
workbook.SaveAs("HelloWorld.xlsx");
whats also really amazing about this approach is that you can put your dataset table or table into the workbook like such
var wb = new XLWorkbook();
var dataTable = GetTable("Information");
// Add a DataTable as a worksheet
wb.Worksheets.Add(dataTable);
wb.SaveAs("AddingDataTableAsWorksheet.xlsx");
the dll is here
i want to export gridview to excel file but the problem is that i have images in gridview which is stored in database table..by the way i storing the whole images not the path of the image and i want to export the images as well..here is the code
but when i run this it give exceptions.. please help..
Thank You
saveFileDialog1.Filter = "Excel (*.xls)|*.xls";
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
if (!saveFileDialog1.FileName.Equals(String.Empty))
{
FileInfo f = new FileInfo(saveFileDialog1.FileName);
if (f.Extension.Equals(".xls"))
{
Excel.Application xlApp;
Excel.Workbook xlWorkBook;
Excel.Worksheet xlWorkSheet;
object misValue = System.Reflection.Missing.Value;
xlApp = new Excel.ApplicationClass();
xlWorkBook = xlApp.Workbooks.Add(misValue);
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
int i = 0;
int j = 0;
for (int h = 1; h < grid.Columns.Count + 1; h++)
{
xlWorkSheet.Cells[1, h] = grid.Columns[h - 1].HeaderText;
}
for (i = 0; i <= grid.RowCount - 1; i++)
{
for (j = 0; j <= grid.ColumnCount - 1; j++)
{
DataGridViewCell cell = grid[j, i];
xlWorkSheet.Cells.Borders.LineStyle = Excel.XlLineStyle.xlContinuous;
xlWorkSheet.Columns.AutoFit();
xlWorkSheet.Cells[i + 2, j + 1] = cell.FormatedValue;
}
}
xlWorkBook.SaveAs(saveFileDialog1.FileName, Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
xlWorkBook.Close(true, misValue, misValue);
xlApp.Quit();
releaseObject(xlWorkSheet);
releaseObject(xlWorkBook);
releaseObject(xlApp);
MessageBox.Show("Excel file created , you can find the file " + saveFileDialog1.FileName);
}
else
{
MessageBox.Show("Invalid file type");
}
}
else
{
MessageBox.Show("You did pick a location " +
"to save file to");
}
}
Here is the picture of excel sheet but in the picture column pictures doesn't show up but the text "System.drawing.bitmap"