I receive some reports in an xslx file that has 2 sheets, the data is good but there's no formatting done on the file. Most of the posts I found talk about formatting the file while creating it, but I'm wondering if there's a way I can work the file with c# code after receiving it (ex : fit columns to content)?
Thank you.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ClosedXML;
using Excel = Microsoft.Office.Interop.Excel;
using Microsoft.CSharp;
using DocumentFormat.OpenXml.Office.Excel;
namespace ExcelFormatter
{
class MainScript
{
public static void Main(string[] args)
{
string file = args[0];
Excel.Application xlApp;
Excel.Workbook xlWorkBook;
Excel.Worksheet xlWorkSheet;
object misValue = System.Reflection.Missing.Value;
Excel.Range chartRange;
xlApp = new Excel.Application();
xlWorkBook = xlApp.Workbooks.Add(file);
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
chartRange = xlWorkSheet.get_Range("A1", "F1");
chartRange.Cells.Font.Bold = true;
xlWorkBook.Save();
xlWorkBook.Close(true, file, misValue);
xlApp.Quit();
}
}
}
I use ClosedXML to manipulate Excel files that have been created using the OpenXML standard. It found it to be easy to use and allowed me to do a lot of things to my documents. Hope this helps.
Wade
Here is an example of what I have done. It is in VB.Net, but you should be able to convert it with no problem.
'Open the workbook and then open the worksheet I want to work with.
Dim workbook = New XLWorkbook("<filepath>")
Dim worksheet = workbook.Worksheet("<worksheetname>")
' Throw an exception if there is no sheet.
If worksheet Is Nothing Then
Throw New ArgumentException("Sheet is missing")
End If
'Set number formatting. You can look at the closedxml documentation to see what the number should be
worksheet.Cell("G5").Style.NumberFormat.SetNumberFormatId(1)
'Merge and style a group of cells
Dim cellRange = "A1:A12"
worksheet.Range(cellRange).Merge.Value = colName
worksheet.Range(cellRange).Style.Fill.BackgroundColor = XLColor.Black
worksheet.Range(cellRange).Style.Font.FontColor = XLColor.White
worksheet.Range(cellRange).Style.Alignment.Horizontal = XLAlignmentHorizontalValues.Center
'Auto adjust the column widths
worksheet.Columns.AdjustToContents()
workbook.SaveAs("<filename>")
You can use EasyXLS to import the xlsx file and after that to apply the format that you need:
// Create an instance of the class that imports XLSX files
ExcelDocument workbook = new ExcelDocument();
// Import XLSX file
workbook.easy_LoadXLSXFile(filePath);
// Get the table of data from the first sheet
ExcelTable xlsTable = ((ExcelWorksheet)workbook.easy_getSheetAt(0)).easy_getExcelTable();
// Create the formatting style for cells
ExcelStyle xlsStyle = new ExcelStyle();
xlsStyle.setHorizontalAlignment(Alignment.ALIGNMENT_LEFT);
xlsStyle.setForeground(Color.DarkGray);
//Apply the formatting to A1 cell
xlsTable.easy_getCell(0, 0).setStyle(xlsStyle);
// Resave the XLSX file
workbook.easy_WriteXLSXFile(newFormattedFilePath);
Check this link on formatting Excel cells fro more specific details.
Related
How do I change the view style of Excel Worksheet In Excel interop to a Normal style?
Like this:
Just have no idea :(
Does someone know?
i see just one solution, you have to use ActiveWindow.View: a sample to use it
using Excel = Microsoft.Office.Interop.Excel;
object missing = System.Reflection.Missing.Value;
Excel.Application excel = new Excel.Application();
Excel.Workbooks wbs = excel.Workbooks;
Excel.Workbook wb = wbs.Open(#"d:\test.xlsm");
Excel.Worksheet sheet = wb.ActiveSheet;
// set the view style
excel.ActiveWindow.View = XlWindowView.xlNormalView;
object filename = #"d:\test1.xlsm";
wb.SaveAs(filename);
wbs.Close();
excel.Quit();
if you have more Worksheets, you have to do that on each Worksheet...
I have a macro-enabled Excel file "D:\MyTests\ExcelTests\template.xlsm" with no data in it, only the VBA code, and my C# code needs to output a workbook data over there. Normally I output workbook data like this:
Excel.Application application = new Excel.Application();
Excel.Workbook workbook = application.Workbooks.Add();
Excel.Worksheet worksheet = workbook.Sheets[1];
Excel.Worksheet worksheet2 = workbook.Sheets[2];
// populate worksheets with some data
DataTable2Worksheet(tableMain, worksheet, verSize);
DataTable2Worksheet(tableExtra, worksheet2, 0);
string fileName = #"D:\MyTests\ExcelTests\newFile";
if (File.Exists(fileName ))
{
File.Delete(fileName );
}
workbook.SaveAs(fileName);
workbook.Close();
Marshal.ReleaseComObject(application);
but this creates a new file (which cannot be macros enabled programmatically). If I want to output the workbook to existing file
string existingFile = #"D:\MyTests\ExcelTests\template.xlsm"
the method
workbook.SaveAs(existingFile );
won't work. So, what should I do instead? Thanks.
Save the file specifically in xlOpenXMLWorkbookMacroEnabled format:
string existingFile = #"D:\MyTests\ExcelTests\template.xlsm"
workbook.SaveAs(existingFile, 52);
I am trying to add a button on an excel worksheet.
According to the example from internet, I am trying to do following code.
using Excel = Microsoft.Office.Interop.Excel;
using VBIDE = Microsoft.Vbe.Interop;
private static void excelAddButtonWithVBA()
{
Excel.Application xlApp = new Excel.Application();
Excel.Workbook xlBook = xlApp.Workbooks.Open(#"PATH_TO_EXCEL_FILE");
Excel.Worksheet wrkSheet = xlBook.Worksheets[1];
Excel.Range range;
try
{
//set range for insert cell
range = wrkSheet.get_Range("A1:A1");
//insert the dropdown into the cell
Excel.Buttons xlButtons = wrkSheet.Buttons();
Excel.Button xlButton = xlButtons.Add((double)range.Left, (double)range.Top, (double)range.Width, (double)range.Height);
//set the name of the new button
xlButton.Name = "btnDoSomething";
xlButton.Text = "Click me!";
xlButton.OnAction = "btnDoSomething_Click";
buttonMacro(xlButton.Name, xlApp, xlBook, wrkSheet);
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
}
xlApp.Visible = true;
}
But it keeps saying "Excel does not contain Button"
What reference should I include to use Button property?
As far as I can tell, Excel.Buttons and Excel.Button do not exist. Instead it is suggested that the correct reference is Microsoft.Office.Tools.Excel.Controls.Button (not Microsoft.Office.Interop.Excel as you are using). This example is from the source below
Excel.Application xlApp = new Excel.Application();
Excel.Workbook xlBook = xlApp.Workbooks.Open(#"PATH_TO_EXCEL_FILE");
Excel.Worksheet worksheet = xlBook.Worksheets[1];
Excel.Range selection = Globals.ThisAddIn.Application.Selection as Excel.Range;
if (selection != null)
{
Microsoft.Office.Tools.Excel.Controls.Button button =
new Microsoft.Office.Tools.Excel.Controls.Button();
worksheet.Controls.AddControl(button, selection, "Button");
}
Source: Adding Controls to a Worksheet at Run Time in an Application-Level Project http://msdn.microsoft.com/en-us/library/cc442817.aspx
Using Lesley.Oakey's method requires you to be using the VSTO extension methods in Microsoft.Tools.Office.Excel.
If you are not using them, then you will not be able to access the Worksheet.Controls property.
Best to just use the Worksheet.Shapes container and add a new shape. There's a great post about this here:
Add excel vba code to button using c#
I am writing a program in C# for analysing a structure details in an earth quake.I have a lot of data and want to put them in a excel file.
I mean i need a function like this :
public void excel(int sheet_no,int row,int column,string value)
Is there any way to parse the text file and Put this data in Excel sheet ?
use this :
Microsoft.Office.Interop.Excel.Application app = new Microsoft.Office.Interop.Excel.Application();
Workbooks workbooks;
_Workbook workbook;
_Workbook workbook2;
Sheets sheets;
_Worksheet worksheet;
app.Visible = false;
workbooks = app.Workbooks;
workbook = workbooks.Add(XlWBATemplate.xlWBATWorksheet);
sheets = workbook.Worksheets;
worksheet = (_Worksheet)sheets.get_Item(1);
worksheet.Cells[row, column] = value;
workbook.Saved = true;
workbook.SaveAs(output_file);
app.UserControl = false;
app.Quit();
Take a look at ClosedXml
Code sample:
var workbook = new XLWorkbook();
var worksheet = workbook.Worksheets.Add("Sample Sheet");
worksheet.Cell("A1").Value = "Hello World!";
workbook.SaveAs("HelloWorld.xlsx");
But if you are dealing with a lot of data, consider using a database like sqlserver.
It provides a lot of analysis tools.
You can connect it as a datasource to excel too.
For now, I am providing links for you to read # Excel Tasks and code samples # Excel controls in ASP.net. If you're still confused, I may be able to find code samples from my projects or the Internet, which are not hard to find.
Look at link Workbook Open (create) method to create Workbooks, and link Workbook Open method to open Workbooks.
I am trying to do the following using c# code:
Hide some rows in excel.
Clear all data and formats in excel sheet.
Put other data to excel sheet.
I would like the hidden rows still remain hidden.
Is it possible?
Thank You!
I've had great results using ClosedXML to manipulate excel spreadsheets.
While I haven't tried your case I've done similar things. In my case I put my private data into a new worksheet and hide that, which ClodedXML made simple.
Here's a sample code that can get you going....
//Create an Excel App
Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel._Workbook xlWorkBook = null;
Microsoft.Office.Interop.Excel._Worksheet xlWorksheet;
//Open a Workbook
xlWorkBook = xlApp.Workbooks.Open(#"d:\test.xlsx");
xlWorksheet = (Microsoft.Office.Interop.Excel.Worksheet)xlWorkBook.Sheets[1];
//My Workbook contains 10 rows with some data and formatting
//I Hide rows 3, 4 & 5
Microsoft.Office.Interop.Excel.Range hiddenRange = xlWorksheet.get_Range("A3:C5");
hiddenRange.EntireRow.Hidden = true;
//Get the entire sheet and Clear everything on it including data & formatting
Microsoft.Office.Interop.Excel.Range allRange = xlWorksheet.UsedRange;
allRange.Clear();
//Now Add some new data, say a Title on the first cell, and some more data in a loop later
xlWorksheet.Cells[1, 1] = "Title";
for (int i = 6; i < 10; i++)
{
xlWorksheet.Cells[i, 1] = i.ToString();
}
xlApp.Visible = true;
Thats it....
Store them in a variable and hide them again after you have populated excel with data.