I need to create a very big Excel file, but excel file in one worksheet can contain up to 65k rows. So, i want to divide all my info into several worksheets dynamical.
This is my approximate code
//------------------Create Excel App--------------------
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(numberOfLetters);
foreach (string letter in letters)
{
xlWorkSheet.Cells[rowIndex, 1] = letter;
rowIndex++;
}
xlWorkBook.SaveAs(pathXL, Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
xlWorkBook.Close(true, misValue, misValue);
xlApp.Quit();
How I can add new worksheet inside of my foreach loop and using some condition give a name to worksheet (which user can see in Excel at the bottom of the page in list)?
Some like that
foreach (string letter in letters)
{
if (letter == SOME)
{
AddNewWorksheet and give name SOME
}
xlWorkSheet.Cells[rowIndex, 1] = letter;
rowIndex++;
}
And how to save all worksheets at the end?
To add a new worksheet to the workbook use this code:
var xlSheets = xlWorkBook.Sheets as Excel.Sheets;
var xlNewSheet = (Excel.Worksheet)xlSheets.Add(xlSheets[1], Type.Missing, Type.Missing, Type.Missing);
xlNewSheet.Name = "newsheet";
// Uncomment a line below if you want the inserted sheet to be the last one
//xlWorkBook.Sheets.Move(After: xlWorkBook.Sheets.Count);
To save the workbook call Save() method:
xlWorkBook.Save();
This is the correct code that is given in MSDN.
Excel.Worksheet newWorksheet;
newWorksheet = (Excel.Worksheet)Globals.ThisWorkbook.Worksheets.Add(
missing, missing, missing, missing);
For more information please click the link
In General when you want to create new sheet just do :
var worksheet = (Microsoft.Office.Interop.Excel.Worksheet)workbook.Worksheets.Add();
knowing that you already created the workbook like below :
var workbook = excel.Workbooks.Add(Type.Missing);
You are limited to 65,000 records with .xls , but if you are "allowed" to step beyond .xls / 2003 and into 2007 and above with .xlsx you should have a lot more rows.
Side note, nothing to do with your question, but a while back I had export to excel issues with RDLC and sheet names I renamed using NPOI library, since then I started using NPOI a lot more it is free /open source and very powerful (ported from Java POI to .net NPOI) again while I say it is not really a part of what your question is I wouldn't be surprised if it had examples on doing this (no I don't work for them ) http://npoi.codeplex.com/
Here is the code I had written for renaming sheets (which ends up re-creating the sheets with another memorystream
------------------------------------------------------------
var excelHelper = new ExcelHelper(bytes);
bytes = excelHelper.RenameTabs("Program Overview", "Go Green Plan", "Milestones", "MAT and EOC", "Annual Financials", "Risk Log", "Risk & Opportunity Log", "RAIL", "Meeting Minutes");
Response.BinaryWrite(bytes);
Response.End();
------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using NPOI.HSSF.UserModel;
namespace Company.Project.Core.Tools
{
public class ExcelHelper
{
private byte[] _ExcelFile;
public ExcelHelper(byte[] excelFile)
{
_ExcelFile = excelFile;
}
public byte[] RenameTabs(params string[] tabNames)
{
byte[] bytes = null;
using (MemoryStream ms = new MemoryStream())
{
ms.Write(_ExcelFile, 0, _ExcelFile.Length);
var workBook = new HSSFWorkbook(ms, true);
if (tabNames != null)
{
using (MemoryStream memoryStream = new MemoryStream())
{
for (int i = 0; i < tabNames.Length; i++)
{
workBook.SetSheetName(i, tabNames[i]);
}
workBook.Write(memoryStream);
bytes = memoryStream.ToArray();
}
}
}
_ExcelFile = bytes;
return bytes;
}
}
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 have generated the excel file using C# coding as shown below
C# Coding:
protected void Page_Load(object sender, EventArgs e)
{
var doc = new SpreadsheetDocument(#"D:\JOSEPH\GenerateExcelSheet\OpenXmlPackaging.xlsx");
Worksheet sheet1 = doc.Worksheets.Add("My Sheet");
sheet1.Cells[1, 1].Value = "Test";
sheet1.Cells["A1"].Value = 1;
sheet1.Cells["C3"].Style = new OpenXmlPackaging.Style {
Borders = new Borders(BorderStyles.Thick),
Font = new Font
{
Name = "Consolas",
Size = 10,
Style = FontStyles.DoubleUnderline | FontStyles.Bold
},
NumberFormat = new NumberFormat("#,##0.0;[Red](#,##0.0)"),
Alignment = new Alignment
{
HorizontalAlignment = HorizontalAlignment.Right,
VerticalAlignment = VerticalAlignment.Top,
WrapText = true,
Rotation = 45
},
};
sheet1.Cells.CreateRange("B10:D5").MergeCells();
sheet1.AutoFitColumns();
sheet1.SetColumnWidth(3, 12);
}
but when i tried to open the excel file, a message box appears as " "
The short answer is that you shouldn't be trying to create an Excel file on the server like this. There are technical issues and licensing issues of using the Excel API to do this - you can read more here http://support.microsoft.com/default.aspx/kb/257757
The technical problems may well explain why you're file is corrupt.
The better approach would be to use a library that doesn't rely on the Excel API, I listed a few in my question/answer here Reading Excel Files as a Server Process that may help you.
Use this for open Excel:
ApplicationClass excel = new ApplicationClass();
Worksheet sheet1 = Activate(excel);
//insert you'r code
Use this for save and close Excel:
excel.Visible = true;
object misValue = System.Reflection.Missing.Value;
sheet1.SaveAs(filename, XlFileFormat.xlWorkbookDefault, misValue, misValue, misValue, misValue, misValue, misValue, misValue, misValue);
excel.Application.Quit();
excel.Quit();
Marshal.ReleaseComObject(ws);
Marshal.ReleaseComObject(excel);
excel = null;
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 am using Excel Interop to work with some excel sheets. In a worksheet, I need to iterate through the rows, and if the first cell in the row is empty then I need to delete the entire row iteself. I tried the following-
Excel.Range excelRange = sheet.UsedRange;
foreach (Excel.Range row in excelRange.Rows)
{
String a = ((Excel.Range)row.Cells[Type.Missing, 1]).Value2 as String;
if (a == null || a == "")
{
((Excel.Range)row).Delete(Type.Missing);
}
}
This was not working at all. Is there any different way to do this?
And, is there any quick way to find and remove all formula in a Worksheet?
Let's say your Excel file looks like this.
The best way to delete rows would be to use Excel's inbuilt feature called Autofilter which will filter Col A for blank values and then deleting the entire rows in one go.
TRIED AND TESTED (In VS 2010 Ultimate)
Note: I have changed few lines which I feel could error out in VS 2008. Since I don't have VS 2008, I couldn't test it there. If you get any errors do let me know and I will rectify it.
//~~> Open File
private void button1_Click(object sender, EventArgs e)
{
Microsoft.Office.Interop.Excel.Application xlexcel;
Microsoft.Office.Interop.Excel.Workbook xlWorkBook;
Microsoft.Office.Interop.Excel.Worksheet xlWorkSheet;
Microsoft.Office.Interop.Excel.Range xlRange;
Microsoft.Office.Interop.Excel.Range xlFilteredRange;
xlexcel = new Excel.Application();
xlexcel.Visible = true;
//~~> Open a File
xlWorkBook = xlexcel.Workbooks.Open("C:\\MyFile.xlsx", 0, false, 5, "", "", true,
Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
//~~> Work with Sheet1
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
//~~> Get last row in Col A
int _lastRow = xlWorkSheet.Cells.Find(
"*",
xlWorkSheet.Cells[1,1],
Excel.XlFindLookIn.xlFormulas,
Excel.XlLookAt.xlPart,
Excel.XlSearchOrder.xlByRows,
Excel.XlSearchDirection.xlPrevious,
misValue,
misValue,
misValue
).Row ;
//~~> Set your range
xlRange = xlWorkSheet.Range["A1:A" + _lastRow];
//~~> Remove any filters if there are
xlWorkSheet.AutoFilterMode=false;
//~~> Filter Col A for blank values
xlRange.AutoFilter(1, "=", Excel.XlAutoFilterOperator.xlAnd, misValue, true);
//~~> Identigy the range
xlFilteredRange = xlRange.Offset[1,0].SpecialCells(Excel.XlCellType.xlCellTypeVisible,misValue);
//~~> Delete the range in one go
xlFilteredRange.EntireRow.Delete(Excel.XlDirection.xlUp);
//~~> Remove filters
xlWorkSheet.AutoFilterMode = false;
//~~> Close and cleanup
xlWorkBook.Close(true, misValue, misValue);
xlexcel.Quit();
releaseObject(xlRange);
releaseObject(xlFilteredRange);
releaseObject(xlWorkSheet);
releaseObject(xlWorkBook);
releaseObject(xlexcel);
}
private void releaseObject(object obj)
{
try
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
obj = null;
}
catch (Exception ex)
{
obj = null;
MessageBox.Show("Unable to release the Object " + ex.ToString());
}
finally
{
GC.Collect();
}
}
Output