I am trying to convert excel VBA code to c#. This code must be executed outside excel and I am going to convert my excel macros to do so. Here is the code to convert
ActiveWindow.Zoom = 85
Range("A1").Select
Range(Selection, Selection.End(xlToRight)).Select
With Selection
.HorizontalAlignment = xlCenter
.VerticalAlignment = xlBottom
.WrapText = True
.Orientation = 0
.AddIndent = False
.IndentLevel = 0
.ShrinkToFit = False
.ReadingOrder = xlContext
.MergeCells = False
End With
Cells.Select
Here is what I got so far:
var excelApp = new Microsoft.Office.Interop.Excel.Application();
excelApp.Visible = true;
excelApp.ActiveWindow.Zoom = 85;
excelApp.Range["A1"].Select();
I cannot figure out the rest below the Range("A1").Select. Any help on this
The with statement is a VB thing only, with c# you have to create a variable and call each of the properties from that variable explicitly
ActiveWindow.Zoom = 85;
Range["A1"].Select();
Range(Selection, Selection.End(xlToRight)).Select();
Selection.HorizontalAlignment = xlCenter;
Selection.VerticalAlignment = xlBottom;
Selection.WrapText = true;
Selection.Orientation = 0;
Selection.AddIndent = false;
Selection.IndentLevel = 0;
Selection.ShrinkToFit = false;
Selection.ReadingOrder = xlContext;
Selection.MergeCells = false;
Cells.Select();
(this is just a sample, do adjust your COM handling as required)
EDIT: Changed brackets to square brackets one the second line.
You need the namespace "Microsoft.Office.Interop.Excel".
using Microsoft.Office.Interop.Excel;
MyClass{
...
var app = new Application { Visible = true, ScreenUpdating = true, DisplayAlerts = false };
Workbook book = app.Workbooks.Open(path); //path is the fullFileName as string
Worksheet sheet = book.Worksheets[1];
Range range = sheet.get_Range("A1", "A1");
range.Select();
range.HorizontalAlignment = Constants.xlCenter;
range.VerticalAlignment = Constants.xlBottom;
range.WrapText = true;
range.Orientation = 0;
range.AddIndent = false;
range.IndentLevel = 0;
range.ShrinkToFit = false;
range.ReadingOrder = Constants.xlContext;
range.MergeCells = false;
}
Enjoy it!
Related
When I try to find a value that is not saved in excel I can't stop loops and get a message from the MessageBox
killExcel();
OpenFileDialog file = new OpenFileDialog();
string filename = Path.GetFileName(file.FileName);
if (file.ShowDialog() == DialogResult.OK) //if there is a file chosen by the user
{
Boolean chc = false;
var Excel = new Microsoft.Office.Interop.Excel.Application();
//var xlWB = Excel.Workbooks.Open("C:/Users/User/Desktop/ttt.xlsx");
var xlWB = Excel.Workbooks.Open(Path.GetFullPath(file.FileName));
var xlSht = xlWB.Worksheets[1];
Microsoft.Office.Interop.Excel.Range range = xlSht.Columns[1];
Microsoft.Office.Interop.Excel.Range findRange;
object missing = System.Reflection.Missing.Value;
findRange = range.Find(id_v.Text, missing,
Microsoft.Office.Interop.Excel.XlFindLookIn.xlValues,
Microsoft.Office.Interop.Excel.XlLookAt.xlPart,
Microsoft.Office.Interop.Excel.XlSearchOrder.xlByRows,
Microsoft.Office.Interop.Excel.XlSearchDirection.xlNext, false, missing, missing);
string result = "";
int a = range.Rows.Count;
if (findRange != null)
{
while (chc==false)
{
for (int i = 1; i <= a; i++)
{
result = Convert.ToString(xlSht.Cells[i, findRange.Column].Value);
if (result == id_v.Text && result != null)
{
id.Text = result;
chc = true;
break;
}
}
if (chc==false) {
MessageBox.Show("Not found!");
break;
}
}
}
}
Sorry I'm just a beginner in programming and I can't understand why the loop is not stopping when the value is not founded
Your while (chc==false) will always return false if the value is not found keeping it in the infinite loop.
Remove the while(csc=false) loop. The for loop accomplishes what you are trying to do and will exit if it finds the entry without the outer while loop. When the for loop exits, either csc will be true because you set it when the entry was found or csc will be false because you initialized it to false before entering the for loop.
I want to format all cells of the spreadsheet as text before loading it with the datatable.
Here is the sample code I am using
StringBuilder sbitems = new StringBuilder();
sbitems.Append(#"select * from Items");
SqlDataAdapter daitems = null;
DataSet dsitems = null;
daitems = new SqlDataAdapter(sbitems.ToString(), constate);
daitems.SelectCommand.CommandTimeout = 0;
dsitems = new DataSet("Items");
daitems.Fill(dsitems);
app.Workbook.Worksheets.Add("Items").Cells["A1"].LoadFromDataTable(dsitems.Tables[0], true);
Excel.ExcelWorksheet worksheet2 = workBook.Worksheets["Items"];
using (var rngitems = worksheet2.Cells["A1:BH1"])//Giving colour to header
{
rngitems.Style.Font.Bold = true;
rngitems.Style.Fill.PatternType = ExcelFillStyle.Solid;
rngitems.Style.Fill.BackgroundColor.SetColor(Color.Yellow);
rngitems.Style.Font.Size = 11;
rngitems.AutoFitColumns();
}
worksheet2.Cells["A1:BH1"].AutoFitColumns();
worksheet2.Cells["A1:BH1"].Style.Font.Bold = true;
app.SaveAs(new System.IO.FileInfo(#"D:\ItemsData\testfileexcelnew.xlsx"));
Try setting Number format as #
ex: rngitems.Style.Numberformat.Format = "#";
# formats cell as Text.
Reference : Force EPPLUS to read as text
possibly duplicate of above thread.
In c#, Rich text content are saved to database in below format
< b>Hello< /b>.
I need to export this to MS Excel sheet as Hello (with bold letters)
When ever i try to export the content in excel , its not showing in rich text. Kindly help me . Thanks,
var workbook = new HSSFWorkbook();
var sheet = workbook.CreateSheet("");
int rowNumber = 1;
NPOI.SS.UserModel.IFont font = workbook.CreateFont();
font.Boldweight = (short)(NPOI.SS.UserModel.FontBoldWeight.BOLD);
font.FontHeight = 210;
font.FontName = "Calibri";
NPOI.SS.UserModel.ICellStyle headerCell = workbook.CreateCellStyle();
headerCell.FillBackgroundColor = NPOI.SS.UserModel.IndexedColors.GREY_25_PERCENT.Index;
headerCell.FillForegroundColor = NPOI.SS.UserModel.IndexedColors.GREY_25_PERCENT.Index;
headerCell.FillPattern = NPOI.SS.UserModel.FillPatternType.SOLID_FOREGROUND;
headerCell.VerticalAlignment = NPOI.SS.UserModel.VerticalAlignment.CENTER;
headerCell.WrapText = true;
headerCell.SetFont(font);
headerCell.BorderBottom = NPOI.SS.UserModel.BorderStyle.THIN;
headerCell.BorderLeft = NPOI.SS.UserModel.BorderStyle.THIN;
headerCell.BorderRight = NPOI.SS.UserModel.BorderStyle.THIN;
headerCell.BorderTop = NPOI.SS.UserModel.BorderStyle.THIN;
NPOI.SS.UserModel.IFont fontShort = workbook.CreateFont();
fontShort.Boldweight = (short)(NPOI.SS.UserModel.FontBoldWeight.NORMAL);
fontShort.FontName = "Calibri";
NPOI.SS.UserModel.ICellStyle normalCell = workbook.CreateCellStyle();
normalCell.FillBackgroundColor = 50;
normalCell.VerticalAlignment = NPOI.SS.UserModel.VerticalAlignment.CENTER;
normalCell.WrapText = true;
normalCell.SetFont(fontShort);
normalCell.BorderBottom = NPOI.SS.UserModel.BorderStyle.THIN;
normalCell.BorderLeft = NPOI.SS.UserModel.BorderStyle.THIN;
normalCell.BorderRight = NPOI.SS.UserModel.BorderStyle.THIN;
normalCell.BorderTop = NPOI.SS.UserModel.BorderStyle.THIN;
NPOI.SS.UserModel.ICellStyle emptyCell = workbook.CreateCellStyle();
emptyCell.SetFont(font);
emptyCell.BorderBottom = NPOI.SS.UserModel.BorderStyle.NONE;
emptyCell.BorderLeft = NPOI.SS.UserModel.BorderStyle.NONE;
emptyCell.BorderRight = NPOI.SS.UserModel.BorderStyle.NONE;
emptyCell.BorderTop = NPOI.SS.UserModel.BorderStyle.NONE;
var headerRow = sheet.CreateRow(0);
var output ="<b>HelloWorld</b>"
var row = sheet.CreateRow(rowNumber++);
row.CreateCell(0).SetCellValue(output);
row.Cells[0].CellStyle = normalCell;
I am using VS2013 Ultimate, with Office 2013 (PowerPoint, Excel and Word all installed). I am coding in C#.
I am creating a PowerPoint presentation using C#. So far, I have managed to accomplish everything that I have wanted to do. However, I am having problems attempting to create a chart. My understanding is that Excel is used to manage the data (in a worksheet). I have the following code, which will produce a chart with two series in a PowerPoint slide. The problem is that 'sometimes' the chart does not get added to the slide. It gets added, the worksheet appears and the data is modified and the chart disappears from the slide! I also notice 2 instances of Excel firing up but I cannot understand why. Can anyone shed any light on this please? Thanks.
public void CreateChart(PPT.Slide slide)
{
slide.Layout = PPT.PpSlideLayout.ppLayoutBlank;
var chart = slide.Shapes.AddChart(XlChartType.xlLine, 10f, 10f, 900f, 400f).Chart;
var workbook = (EXCEL.Workbook)chart.ChartData.Workbook;
workbook.Windows.Application.Visible = true;
var dataSheet = (EXCEL.Worksheet)workbook.Worksheets[1];
dataSheet.Cells.ClearContents();
dataSheet.Cells.Range["A1"].Value2 = "Bananas";
dataSheet.Cells.Range["A2"].Value2 = "Apples";
dataSheet.Cells.Range["A3"].Value2 = "Pears";
dataSheet.Cells.Range["A4"].Value2 = "Oranges";
dataSheet.Cells.Range["B1"].Value2 = "1000";
dataSheet.Cells.Range["B2"].Value2 = "2500";
dataSheet.Cells.Range["B3"].Value2 = "4000";
dataSheet.Cells.Range["B4"].Value2 = "3000";
var sc = (PPT.SeriesCollection)chart.SeriesCollection();
do
{
var seriesToDelete = sc.Item(1);
seriesToDelete.Delete();
}
while (sc.Count != 0);
var series1 = sc.NewSeries();
series1.Name = "Pauls Series";
series1.XValues = "'Sheet1'!$A$1:$A$2";
series1.Values = "'Sheet1'!$B$1:$B$2";
series1.ChartType = XlChartType.xlLine;
var series2 = sc.NewSeries();
series2.Name = "Seans Series";
series2.XValues = "'Sheet1'!$A$1:$A$2";
series2.Values = "'Sheet1'!$B$3:$B$4";
series2.ChartType = XlChartType.xlLine;
chart.HasTitle = true;
chart.ChartTitle.Font.Italic = true;
chart.ChartTitle.Text = "My First Chart!";
chart.ChartTitle.Font.Size = 12;
chart.ChartTitle.Font.Color = Color.Black.ToArgb();
chart.ChartTitle.Format.Line.Visible = Microsoft.Office.Core.MsoTriState.msoTrue;
chart.ChartTitle.Format.Line.ForeColor.RGB = Color.Black.ToArgb();
chart.HasLegend = true;
chart.Legend.Font.Italic = true;
chart.Legend.Font.Size = 10;
chart.Refresh();
}
so, putting a chart.refresh() within the Do{} block has resolved my problems! How odd!?!
As you can see, the no. of columns names generated from column 4 are unknown. How can I set the range, so that I can apply the styles.
using Microsoft.Office.Interop;
using Excel = Microsoft.Office.Interop.Excel;
private void OpenExcel()
{
Excel.Application app = new Excel.Application();
Excel.Workbook wb = null;
Excel.Worksheet ws = null;
Excel.Range range = null;
app.visible = true;
wb = app.Workbooks.Add(1);
ws = (Excel.Worksheet)wb.WorkSheets[1];
//range = ws.get_Range("A1","D1");
ws.Cells[1,1]="Date";
ws.Cells[1,2]="Code";
ws.Cells[1,3]="Name";
IEnumerable<tblCountry> tbl = objDAL.GetRecords();
int i=4;
foreach(var item in tbl)
{
ws.Cells[1,i] = item.TypeCode;
i++;
}
range.Borders.Color = System.Drawing.Color.Black.ToArgb();
range.Interior.Color = System.Drawing.Color.PeachPuff.ToArgb();
range.Font.Bold = true;
}
Just use 3+ tbl.Count() as the last column?
//remember to initialise tbl first
IEnumerable<tblCountry> tbl = objDAL.GetRecords();
range=ws.get_Range((Excel.Range)ws.Cells[1, 1], (Excel.Range)ws.Cells[1, 3 + tbl.Count()]);
Use the End() function as follows to select row with all the columns.
range = ws.Range("A1").End(xlToLeft).Select
And then perform the Style operations.
range.Borders.Color = System.Drawing.Color.Black.ToArgb();
range.Interior.Color = System.Drawing.Color.PeachPuff.ToArgb();
range.Font.Bold = true;
The start range address is "A1" for this example, but I am sure in your Production code, you'll have the Range address as a parameter or coming from a variable.
For a detailed list of Range selection operations, see here. http://www.ozgrid.com/VBA/ExcelRanges.htm
You can pretty much use any of those VBA methods in this Interop in C#.