I have made a simple inventory interface that will take data from access and show in datagrid view on my interface and then send the information to Excel via button click. This part works as needed but I would like to remove the unused columns and rows after the information is sent. I am currently using VS 2015. I cant figure out what to add to accomplish this.
//send to excel
private void btnExport_Click(object sender, EventArgs e)
{
ActiveControl = txtSerial;
// creating Excel Application
Microsoft.Office.Interop.Excel._Application app = new Microsoft.Office.Interop.Excel.Application();
// creating new WorkBook within Excel application
Microsoft.Office.Interop.Excel._Workbook workbook = app.Workbooks.Add(Type.Missing);
// creating new Excelsheet in workbook
Microsoft.Office.Interop.Excel._Worksheet worksheet = null;
// see the excel sheet behind the program
app.Visible = true;
// get the reference of first sheet. By default its name is Sheet1.
// store its reference to worksheet
worksheet = workbook.Sheets["Sheet1"];
worksheet = workbook.ActiveSheet;
// changing the name of active sheet
worksheet.Name = "Inventory Search";
// storing header part in Excel
for (int i = 1; i < dataGridFB.Columns.Count + 1; i++)
{
worksheet.Cells[1, i] = dataGridFB.Columns[i - 1].HeaderText;
worksheet.Cells[1, i].Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.LightBlue);
worksheet.Cells[1, i].Font.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Black);
worksheet.Cells[1, i].HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignCenter;
worksheet.Cells[1, i].Font.Size = 14;
}
// storing Each row and column value to excel sheet
for (int i = 0; i < dataGridFB.Rows.Count - 1; i++)
{
for (int j = 0; j < dataGridFB.Columns.Count; j++)
{
worksheet.Cells[i + 2, j + 1] = dataGridFB.Rows[i].Cells[j].Value.ToString();
worksheet.Cells[i + 2, j + 1].HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignCenter;
worksheet.Cells[i + 2, j + 1].Font.Size = 12;
worksheet.Columns["A:G"].AutoFit();
}
}
}
Your question is a bit too broad, thus the answer is generic: in order to delete entire Worksheet Column you may use VBA statement like: Columns("C").Delete, or Columns(3).EntireColumn.Delete, or Columns("F:K").Delete. Similar syntax may apply to: Rows(3).Delete.
In order to just hide Rows/Columns use the VBA statement like shown below:
Rows("3:10").EntireRow.Hidden = True
Columns("C").Hidden = True
Hope this may help.
Related
Currently using the Excel print function to Export data from a WPF Datagrid and print it. Below is the code I am using:
private void OnDataGridPrinting(object sender, RoutedEventArgs e)
{
System.Windows.Controls.PrintDialog Printdlg = new System.Windows.Controls.PrintDialog();
if ((bool)Printdlg.ShowDialog().GetValueOrDefault())
{
// creating Excel Application
Microsoft.Office.Interop.Excel._Application app = new Microsoft.Office.Interop.Excel.Application();
// creating new WorkBook within Excel application
Microsoft.Office.Interop.Excel._Workbook workbook = app.Workbooks.Add(Type.Missing);
// creating new Excelsheet in workbook
Microsoft.Office.Interop.Excel._Worksheet worksheet = null;
// see the excel sheet behind the program
app.Visible = false;
// get the reference of first sheet. By default its name is Sheet1.
// store its reference to worksheet
worksheet = workbook.Sheets["Sheet1"];
worksheet = workbook.ActiveSheet;
// changing the name of active sheet
worksheet.Name = SelectedCustomer.CustName;
// storing header part in Excel
CollectionViewSource itemCollectionViewSources;
itemCollectionViewSources = (CollectionViewSource)(FindResource("ItemCollectionViewSources"));
for (int i = 1; i < dgEndOfYear.Columns.Count + 1; i++)
{
**worksheet.Cells[1, i] = dgEndOfYear.Columns[i - 1].Header;**
}
// storing Each row and column value to excel sheet
for (int i = 0; i < CustomerEOYTotals.Count - 0; i++)
{
absvwEndOfYearTotal1 line = CustomerEOYTotals[i];
worksheet.PageSetup.CenterHeader = "&UEnd Of Year Report " + CurrentYear;
worksheet.Cells[i + 2, 1] = line.CalendarYear;
worksheet.Cells[i + 2, 2] = line.CustName;
worksheet.Cells[i + 2, 3] = line.MonthName;
worksheet.Cells[i + 2, 4] = line.SumGal.Value.ToString();
worksheet.Cells[i + 2, 5] = line.Manifest;
worksheet.Columns.Cells.Font.FontStyle = Microsoft.Office.Interop.Excel.XlUnderlineStyle.xlUnderlineStyleSingle;
worksheet.Cells.Style.HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignCenter;
worksheet.Columns.ColumnWidth = 14;
}
// Print the workbook
workbook.PrintOut();
The line "worksheet.Cells[1, i] = dgEndOfYear.Columns[i - 1].Header" are the headers from the data grid I have made several attempts to style the headers so they are underlined like the below example when printed out but have had no luck any help would be appreciated:
Found the answer. I can just set the Underline property to true like so:
worksheet.Cells[1, i] = dgCountyEOY.Columns[i - 1].Header;
worksheet.Cells[1, i].Characters.Font.Underline = true;
I have a code that displays a table from an Access database, on my WinForm I have an option to export the table to excel, once the user click on it takes some time to copy all rows to excel, if the user try to close the excel before all cells get transfer to the sheet the application will stop and throw the error System.Runtime.InteropServices.COMException: 'Exception from HRESULT: 0x800AC472'
Here is the code for the "Export to Excel" button I have in my windows form
private void Export_btn_Click(object sender, EventArgs e)
{
Microsoft.Office.Interop.Excel._Application app = new Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel._Workbook workbook = app.Workbooks.Add(Type.Missing);
Microsoft.Office.Interop.Excel._Worksheet worksheet = null;
app.Visible = true;
worksheet = workbook.Sheets["Sheet1"];
worksheet = workbook.ActiveSheet;
for (int i = 1; i < fviAoi_tbl.Columns.Count + 1; i++)
{
worksheet.Cells[1, i] = fviAoi_tbl.Columns[i - 1].HeaderText;
}
for (int i = 0; i < fviAoi_tbl.Rows.Count - 1; i++)
{
for (int j = 0; j < fviAoi_tbl.Columns.Count; j++)
{
if (fviAoi_tbl.Rows[i].Cells[j].Value != null)
{
worksheet.Cells[i + 2, j + 1] = fviAoi_tbl.Rows[i].Cells[j].Value.ToString();
}
else
{
worksheet.Cells[i + 2, j + 1] = "";
}
}
}
}
Any ideas why this is happening or how can I make my application to ignore that error and continue running.
Surround the code line that emit the exception with a try... catch...
https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/exceptions/
In general, Null is probably not what you think it is.
Null is not 0 nor empty string. Null is lack of data. What is the difference between ("") and (null)
Thus, C# and .NET probably throws an error here:
if (fviAoi_tbl.Rows[i].Cells[j].Value != null) because, it does not understand how can you compare some Excel cell with Null and what should it answer. Change the code to:
if (fviAoi_tbl.Rows[i].Cells[j].Value != "" or something similar.
I am creating an excel work book of my daily report. I want the header part to coloured to yellow. All links that are posted either requires a link of the workbook to be opened or are not specific to probelm. I am posting my code here, please suggest how to make Row 6 in yellow color.
string workBookName;
// creating Excel Application
Microsoft.Office.Interop.Excel._Application app = new Microsoft.Office.Interop.Excel.Application();
// creating new WorkBook within Excel application
Microsoft.Office.Interop.Excel._Workbook workbook = app.Workbooks.Add(Type.Missing);
// creating new Excelsheet in workbook
Microsoft.Office.Interop.Excel._Worksheet worksheet = null;
// see the excel sheet behind the program
app.Visible = true;
// get the reference of first sheet. By default its name is Sheet1.
// store its reference to worksheet
worksheet = workbook.Sheets["Sheet1"];
worksheet = workbook.ActiveSheet;
// changing the name of active sheet
workBookName = DateTime.Now.ToString("ddMMMyyyy-HHmmss");
worksheet.Name = workBookName;
worksheet.Cells[1, 1] = "Logistics";
worksheet.Cells[2, 1] = "Tracking Number";
worksheet.Cells[4, 2] = "Date - ";
worksheet.Cells[4, 3] = dateTimePicker1.Value.ToString("dd/MMM/yyyy");
// storing header part in Excel
for (int i = 1; i < dataGridView1.Columns.Count + 1; i++)
{
worksheet.Cells[6, i] = dataGridView1.Columns[i - 1].HeaderText;
// worksheet.get_Range(worksheet.Cells[6, i]).Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Green);
}
// storing Each row and column value to excel sheet
for (int i = 0; i < dataGridView1.Rows.Count - 1; i++)
{
for (int j = 0; j < dataGridView1.Columns.Count; j++)
{
//if (!string.IsNullOrWhiteSpace(dataGridView1.Rows[i].Cells[j].Value))
{
worksheet.Cells[i + 8, j + 1] = dataGridView1.Rows[i].Cells[j].Value;
}
}
}
// save the application
workbook.SaveAs("Tracking Number Report " + workBookName + ".xls", Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
// Exit from the application
app.Quit();
I want row 6, which is the header part in my case to be colored.
if you run this code you will end up with an Excel instance still running because you have not released resources in interop using the .ReleaseComObject call - much more info on this here
I MUCH prefer to use one of the Open XML libraries such as EPPlus for this type of thing. It makes things a lot simpler and makes it easy to color a row.
Try something like this:
using (var excel = new ExcelPackage())
{
var workBookName = DateTime.Now.ToString("ddMMMyyyy-HHmmss");
var worksheet = excel.Workbook.Worksheets.Add(workBookName);
worksheet.Cells[1, 1].Value = "Logistics";
worksheet.Cells[2, 1].Value = "Tracking Number";
worksheet.Cells[4, 2].Value = "Date - ";
worksheet.Cells[4, 3].Value = dateTimePicker1.Value.ToString("dd/MMM/yyyy");
for (int i = 1; i < dataGridView1.Columns.Count + 1; i++)
{
worksheet.Cells[6, i].Value = dataGridView1.Columns[i - 1].HeaderText;
}
worksheet.Cells["6:6"].Style.Fill.PatternType = OfficeOpenXml.Style.ExcelFillStyle.Solid;
worksheet.Cells["6:6"].Style.Fill.BackgroundColor.SetColor(Color.Yellow);
//
//..etc
//
excel.SaveAs(new FileInfo("Tracking Number Report " + workBookName + ".xlsx"));
}
I need to read an excel file after reading it I need to do a mapping
to a DataGridView.
This is the code I've tried:
DataTable dt = new DataTable();
Microsoft.Office.Interop.Excel.Application exlApp = new Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel.Workbook exlWb = exlApp.Workbooks.Open(#"C:\Users\HP8200\Desktop\2003.xls");
Microsoft.Office.Interop.Excel.Worksheet exlWs = exlWb.Sheets["PARAC1"];
Microsoft.Office.Interop.Excel.Range usedRange = exlWs.UsedRange;
int col = Convert.ToInt32(usedRange.Columns.Count);
int row = Convert.ToInt32(usedRange.Rows.Count);
exlApp.Visible = true;
string[,] cellValue = new string[row + 1, col + 1];
for (int j = 1; j <= row - 1; j++)
{
for (int k = 1; k <= col - 1; k++)
{
cellValue[j, k] = exlWs.Cells[j, k + 1].ToString();
dt.Rows[j]["Customer No"] = cellValue[j, 1];
dt.Rows[j]["Card Prog"] = cellValue[j, 2];
dt.Rows[j]["LOS No"] = cellValue[j, 3];
}
}
exlWb.Close();
exlWs = null;
exlWb = null;
exlApp.Quit();
exlApp = null;
dataGridView1.DataSource = dt;
there are some good answers here:
How to read an excel file in C# without using Microsoft.Office.Interop.Excel libraries
It is always a good idea to read an excel file without being required to have office installed and you will see there an answer related to this, there are libraries that can do that for you easily.
Next, try to apply a little SOC ( separation of concerns ) in your code. This means you build a layer responsible for reading your excel files and that one returns some data in a format you can use in the UI. That's the layer you call and then you apply the results of that call to your DataGrid or whatever other UI thing you want to display it in.
I am creating an excel file using a data table in excel interop
Price Profit/Loss%
250.8982989 0.04301071
I have a schema file which has details for design as
1) make all headers bold
2) column definition (weather,string,percentage)
I used this file in fast report export but as such i have to use interop for excel export is there a way i can add that schema file
Excel.Application excelApp = new Excel.Application();
//Create an Excel workbook instance and open it from the predefined location
Excel.Workbook excelWorkBook = excelApp.Workbooks.Add(Excel.XlWBATemplate.xlWBATWorksheet);
//Add a new worksheet to workbook with the Datatable name
Excel.Worksheet excelWorkSheet = (Excel.Worksheet)excelWorkBook.Sheets.Add();
for (int i = 1; i < table.Columns.Count + 1; i++)
{
excelWorkSheet.Cells[1, i] = table.Columns[i - 1].ColumnName;
}
for (int j = 0; j < table.Rows.Count; j++)
{
for (int k = 0; k < table.Columns.Count; k++)
{
excelWorkSheet.Cells[j + 2, k + 1] = table.Rows[j].ItemArray[k].ToString();
}
}
excelWorkBook.SaveAs(#"D:\sample excel.xls");
excelWorkBook.Close();
excelApp.Quit();
i want to show this value in bold and format as % 0.04301071
make this value Bold and round 250.8982989
This all information will be stored in a schema file i want to load that file
or else i want to load that cell as per the columns datatype in datatable
I have tried :-
clmnrange.NumberFormat = (Object)table.Columns[k - 1].DataType;
but it is raising an exception
Regards
EP
As mentioned in above comment:
The NumberFormat property takes a string that uses Excel's formatting
syntax. For example formatting as a percentage (up to) 8 decimal
places is "0.########%"
Here is an example that someone else provided showing how to implement the type of numberingFormat you are describing:
WorkbookStylesPart sp = workbookPart.AddNewPart<WorkbookStylesPart>();
Create a stylesheet:
sp.Stylesheet = new Stylesheet();
Create a numberingFormat:
sp.Stylesheet.NumberingFormats = new NumberingFormats();
// #.##% is also Excel style index 1
NumberingFormat nf2decimal = new NumberingFormat();
nf2decimal.NumberFormatId = UInt32Value.FromUInt32(3453);
nf2decimal.FormatCode = StringValue.FromString("0.0%");
sp.Stylesheet.NumberingFormat.Append(nf2decimal);