Creating Excel Spreadsheet - Library Reference issue - c#

I am attempting to create an Excel spreadsheet in C#. I am using VSE 2010. I added a project reference to
Microsoft Excel 14.0 Object Library
and my using statements include
using Microsoft.Office.Interop.Excel;
however, this code gives an error "the type or namespace could not be found" for all the Excel. statements.
Is there anything else I need to be doing?
class excelsheet
{
private static void CreateWorkbook(string FileName)
{
Excel.Application xl = null;
Excel._Workbook wb = null;
Excel._Worksheet sheet = null;
//VBIDE.VBComponent module = null;
bool SaveChanges = false;
}
}

I'm assuming you are doing this:
using Microsoft.Office.Interop.Excel;
Instead, try changing it to a using statement like:
using Excel = Microsoft.Office.Interop.Excel;

Related

How to copy an excel sheet from workbook A to workbook B

I have the below code to copy Sheet1 from a workbook (test1.xlsx) to another workbook (test2.xlsx). The code doesn't have any errors and it takes forever to execute and I had to stop the code with no change in the files. Please let me know what is wrong.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Excel = Microsoft.Office.Interop.Excel;
namespace Read_from_Excel_file
{
class Program
{
static void Main(string[] args)
{
Excel.Application xlApp = new Excel.Application();
Excel.Workbook test1 = xlApp.Workbooks.Open(#"C:\Users\namokhtar\Desktop\test1.xlsx");
Excel.Workbook test2 = xlApp.Workbooks.Open(#"C:\Users\namokhtar\Desktop\test2.xlsx");
test2.Worksheets.Copy(test1.Worksheets["Sheet1"]);
test2.Save();
test1.Close();
test2.Close();
xlApp.Quit();
}
}
}
I think you need to specify where to copy the worksheet to. So at line
test2.Worksheets.Copy(test1.Worksheets["Sheet1"]);
you have to specify which worksheet in test2 you want to copy the worksheet in. test2.Worksheets["whateverworksheetyouwanttooverwrite"].Copy(test1.Worksheets["Sheet1"]);
Source: (https://learn.microsoft.com/nl-nl/visualstudio/vsto/how-to-programmatically-copy-worksheets?view=vs-2017)

Enable to read cell value from Excel to C# while

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Office.Interop.Excel;
using System.Data.OleDb;
namespace EXCEL_SMS
{
class Program
{
static void Main(string[] args)
{
string path = "C:\\Projects\\ExcelSingleValue\\Test.xlsx ";
Application excel = new Application();
Workbook wb = excel.Workbooks.Open(path);
Worksheet excelSheet = wb.Activesheet;
// Read the first cell
string test = excelSheet.Cells[1, 1].Value.ToString();
// string sValue = (range.Cells[2, 4] as Microsoft.Office.Interop.Excel.Range).Value2.ToString();
wb.Close();
}
}
}
I am getting error at activesheet, I want read cell value from Excel while it's open. Can anyone tell how I can achieve it? I'm using Visual Studio 2012.
there is a mistake in "ActiveSheet" please correct it will work fine, in your code it is "Activesheet" ('s' is a small need to be Capital 'S')
Worksheet excelSheet = wb.ActiveSheet; //wb.Activesheet;
Please see the result I am getting with the same program as below, I am able to get the first Cell from test.xlsx

Format an existing Excel file sheets with C#

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.

Looping through Excel workbooks, copying a range of cells from each and pasting to a master workbook

HI: I am so glad you all are out there because what should be so easy appears not to be for me.
Background: I am trying to use C# to open an Excel Workbook (using OpenFileDialog to select it - called "Gradebook"). Then I loop through multiple Excel workbooks (in a folder I select with FolderBrowserDialog - which saves the filenames in a string[]). I wish to open each workbook one by one, extract a range of data from each workbook and paste it in the "Gradebook". So far capturing the filenames in the array is working and so is the ability to select single workbook and open it.
The Question: I am having problems with the foreach statement. As I loop through the workbooks, the line: Excel.Workbook stdWorkbook = excelApp.Workbooks.Open(stdFile) has an error: "the name stdFile does not exist in the context".
Also, I am rather new to programming and seem to be having problems finding anything that explains interop with Excel and C# in simple enough terms for me to understand. I would greatly appreciate any direction to a good source.
using System;
using System.IO;
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 Excel = Microsoft.Office.Interop.Excel; //Use Project add reference to add the Microsoft Excel Object library, then add this statement
using System.Reflection;
namespace ExcelLoadStdDataToGradingSheet
{
public partial class Form1 : Form
{
public string[] fileNames;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
// select the folder with the student assignment
FolderBrowserDialog fbd = new FolderBrowserDialog();
fbd.Description = "Browse to find Folder with student assignments to open";
fbd.SelectedPath = "C:\\Users\\Robert\\Google Drive\\Programming";
DialogResult result = fbd.ShowDialog();
if (result == DialogResult.OK)
{
string[] fileNames = Directory.GetFiles(fbd.SelectedPath);
System.Windows.Forms.MessageBox.Show("Files found: " + fileNames.Length.ToString(), "Message");
}
}
private void button2_Click(object sender, EventArgs e)
{
// Select the Excel file used for grading and open it
OpenFileDialog dialog = new OpenFileDialog(); // Open dialog box to select desired Excel file. Next 3 line adjust that browser dialog
dialog.Title = "Browse to find Grade Sheet to open";
dialog.InitialDirectory = #"c:\\Users\\Robert\\Google Drive\\Programming";
dialog.ShowDialog();
string GradeExcel = dialog.FileName;
Excel.Application excelApp = new Excel.Application(); //This creates the Excel application instance "excelApp"
excelApp.Visible = true;
Excel.Workbook GradeBook = excelApp.Workbooks.Add(GradeExcel);
// Loop to open every student file, extract filename, name, Red ID, and creation date
foreach (string stdFile in fileNames);
{
// Open student Workbook and copy data from "Hidden" Worksheet
//Excel.Application newApp = new Excel.Application(); //This creates the Excel application instance "newApp"
Excel.Workbook stdWorkbook = excelApp.Workbooks.Open(stdFile); //Open student Workbooks
Excel.Worksheet xlWorksheet = stdWorkbook.Sheets["Hidden"];
Excel.Range xlRange = xlWorksheet.Range["A2:E2"];
// Paste student information to the Grade Sheet
// Workbooks(GradeBook).Sheets("GradingSheet").Range("SetActiveCell").Select.Paste; //' start pasting in "A5";
// SetActiveCell = ActiveCell.Offset(1, 0).Select;
// workbooks("StdWorkbook").close savechanges:=false;
}
// workbooks("Gradingbook").close savechanges:=true;
}
}
}
foreach (string stdFile in fileNames);
The semi-colon at the end of this line terminates the statement immediately, so stdFile is not available in the code further down. Remove the semi-colon.
There is a straight-forward introduction to Excel Interop here at dotnetperls.

Password Protecting an Excel file in C#

Does anyone know the syntax for this? I've been looking everywhere and all I can find is C++ code for this. I'm trying to password protect an excel file programatically using the System.IO.Packaging namespace.
Any ideas?
Additional notes:
I'm NOT using the Excel interop--but instead the System.IO.Packaging namespace to encrypt and password protect the excel file.
If you want an Excel password all you need is something like this:
using Microsoft.Office.Interop.Excel
//create your spreadsheet here...
WorkbookObject.Password = password;
WorkbookObject.SaveAs("spreadsheet.xls")
This requires Excel to be installed.
That's nothing to do with System.IO.Packaging of course, so you might need to restate your question...
It's not possible using System.IO.Packaging. You will have to use Microsoft.Office.Interop.Excel using the Worksheet.SaveAs method. This requires Excel being installed on your target system.
You will have to use the SaveAs method on the Worksheet. It has a parameter to set a password. Here is an example in VB which can be converted to C#
http://www.codeproject.com/KB/office/Excel_Security.aspx
using System.IO;
using Excel=Microsoft.Office.Interop.Excel;
class ExcelUtil
{
public string Filename;
private Excel.Application oexcel;
private Excel.Workbook obook;
private Excel.Worksheet osheet;
public void createPwdExcel()
{
try
{
// File name and path, here i used abc file to be
// stored in Bin directory in the sloution directory
//Filename = (AppDomain.CurrentDomain.BaseDirectory + "abc.xls");
if (File.Exists(Filename))
{
File.Delete(Filename);
}
if (!File.Exists(Filename))
{
// create new excel application
Excel.Application oexcel = new Excel.Application();
oexcel.Application.DisplayAlerts = false;
obook = oexcel.Application.Workbooks.Add(Type.Missing);
oexcel.Visible = true;
Console.WriteLine("Generating Auto Report");
osheet = (Excel.Worksheet)obook.Sheets.Add(Type.Missing, Type.Missing, Type.Missing, Type.Missing);
osheet.Name = "Test Sheet";
osheet.get_Range("A1:G1").Merge();
osheet.get_Range("A1").Value = #"Implementing Password Security on Excel Workbook Using Studio.Net";
osheet.get_Range("A1").Interior.ColorIndex = 5;
osheet.get_Range("A1").Font.Bold = true;
string password = "abc";
obook.WritePassword = password;
obook.SaveAs("Chandra.xlsx");
// otherwise use the folowing one
// TODO: Labeled Arguments not supported. Argument: 2 := 'password'
// end application object and session
osheet = null;
obook.Close();
obook = null;
oexcel.Quit();
oexcel = null;
}
}
catch (Exception ex)
{
}
}
}
Download Microsoft.Office.Interop.Excel from NuGet Package. Password protect Excel file using c# code below
using Excel = Microsoft.Office.Interop.Excel;
Excel.Application xlApp = new Excel.Application();
Excel.Workbook xlWorkbook = xlApp.Workbooks.Open(srcFile);
//protect the whole workbook
xlWorkbook.Password = "passwordString";
xlWorkbook.SaveAs(dstFile);
xlWorkbook.Close();
xlApp.Quit();

Categories

Resources