i'm trying to insert some data to my excel sheet.
My main code returns true/false statement and i need to save that statements to my Registers.xls file.
How do i read and write data from same excel. (Sorry for poor english)
static void Main(string[] args)
{
Excel.Application xlApp;
Excel.Workbook xlWorkbook;
Excel.Worksheet xlWorksheet;
Excel.Range range;
xlApp = new Excel.Application();
xlWorkbook = xlApp.Workbooks.Open(#"E:\VScode\Registers.xls");
xlWorksheet = (Excel.Worksheet)xlWorkbook.Worksheets.get_Item(1);
range = xlWorksheet.UsedRange;
int cl = range.Rows.Count;
string result;
string strRegist;
for (int i = 1; i <= cl;i++)
{
strRegist = (string)(range.Cells[i,3] as Excel.Range).Value2;
result = Convert.ToString(Program.CheckRegister(strRegist));
//Insert result to my sheet
Console.WriteLine(result);
}
xlWorkbook.Close(true, null, null);
xlApp.Quit();
Marshal.ReleaseComObject(xlWorksheet);
Marshal.ReleaseComObject(xlWorkbook);
Marshal.ReleaseComObject(xlApp);
Console.WriteLine();
Console.ReadLine();
}
You could add your data into a datatable and then convert that to an excelsheet and adding that sheet into w/e workbook you want.
using OfficeOpenXml;
using System.Data;
using System.IO;
void SaveTableAsExcelSheet(DataTable dt, string filePath)
{
var fi = new FileInfo(filePath);
using (ExcelPackage pck = new ExcelPackage(fi))
{
ExcelWorksheet ws = pck.Workbook.Worksheets.Add(dt.TableName);
ws.Cells["A1"].LoadFromDataTable(dt, true);
pck.Save();
}
}
Related
I am running a script to format sheets in an existing excel file. Here is what I have now:
public void Main()
{
string datetime = DateTime.Now.ToString("yyyyMMddHHmm");
try
{
string FileName = Dts.Variables["User::DestinationFilePath1"].Value.ToString();
string FolderName = Dts.Variables["User::DestinationFolder1"].Value.ToString();
Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();
xlApp.Visible = false;
Workbook xlWorkbook = xlApp.Workbooks.Open(FileName);
Sheets xlSheets = xlWorkbook.Worksheets;
Worksheet sheet = (Worksheet)xlApp.Worksheets[1];
sheet.Select(Type.Missing);
xlWorkbook.Save();
xlWorkbook.Close(true);
Dts.TaskResult = (int)ScriptResults.Success;
}
catch (Exception exception)
{
// Create Log File for Errors
using (StreamWriter sw = File.CreateText(Dts.Variables["User::DestinationFilePath1"].Value.ToString() + datetime + ".log"))
{
sw.WriteLine(exception.ToString());
Dts.TaskResult = (int)ScriptResults.Failure;
}
}
}
It doesn't do anything at the moment, just opens the workbook and sets the active worksheet. There are 3 different sheets in the workbook that I need to format, so would I be able to do this like so?:
try
{
string FileName = Dts.Variables["User::DestinationFilePath1"].Value.ToString();
string FolderName = Dts.Variables["User::DestinationFolder1"].Value.ToString();
Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();
xlApp.Visible = false;
Workbook xlWorkbook = xlApp.Workbooks.Open(FileName);
Sheets xlSheets = xlWorkbook.Worksheets;
Worksheet sheet = (Worksheet)xlApp.Worksheets[1];
sheet.Select(Type.Missing);
//do work here
Worksheet sheet = (Worksheet)xlApp.Worksheets[2];
sheet.Select(Type.Missing);
//do work here
Worksheet sheet = (Worksheet)xlApp.Worksheets[3];
sheet.Select(Type.Missing);
//do work here
xlWorkbook.Save();
xlWorkbook.Close(true);
Dts.TaskResult = (int)ScriptResults.Success;
}
I am unable to select range using excel interop in C#. Please let me know what am I doing wrong here. I am very new to excel interop
static void Main(string[] args)
{
Excel.Application xlApp = new Excel.Application();
Excel.Workbook xlWorkbook = xlApp.Workbooks.Open("D:\\s1.xlsx");
Excel.Range xlTestRange;
Excel._Worksheet xlWorksheet = xlWorkbook.Sheets[2];
xlTestRange = xlWorksheet.UsedRange;
xlTestRange.Select();
xlWorkbook.Save();
xlWorkbook.Close();
xlApp.UserControl = true;
xlApp.Quit();
}
The following code worked for me in LINQPad:
var xlApp = new Excel.Application();
var xlWorkbook = xlApp.Workbooks.Open(#"path-to-excel-file");
var xlWorksheet = (Excel.Worksheet)xlWorkbook.Sheets[1];
var xlTestRange = xlWorksheet.UsedRange;
xlTestRange.Select();
xlWorkbook.Save();
xlWorkbook.Close();
xlApp.Quit();
I am attempting to add a worksheet to my existing Excel instance using C#, but I get an error of
Object not set to an instance of an object
The line that throws the code is the one that begins with newSheet =
I am not sure why this is being thrown as I declare my variable newSheet and I have instantiated xlApp ---- What do I need to alter in order for this syntax to work as expected?
public static void AddNewSheet()
{
Excel.Application xlApp;
xlApp = new Excel.Application();
Excel.Worksheet Jobs, Estimates;
string filePath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + #"\Test.xlsx";
var xlWorkBook = xlApp.Workbooks.Open(filePath);
Excel.Worksheet newSheet;
//Add a new worksheet to the workbook
newSheet = (Excel.Worksheet)xlApp.Worksheets.Add(System.Reflection.Missing.Value,
xlWorkBook.Worksheets[xlWorkBook.Worksheets.Count],
System.Reflection.Missing.Value,
System.Reflection.Missing.Value);
}
EDIT
Additional Code - to hopefully assist with adding worksheets to already created workbook.
namespace GenerateExcelWorkbookData
{
public partial class Form1 : Form
{
public static Excel.Application xlApp;
public static Excel.Workbook xlWorkBook;
public static Excel.Worksheet xlWorkSheet;
public static Excel.Worksheet newSeet;
Main()
{
//Query Excel To Get DataTable Here
//Excel Info
xlApp = new Excel.Application();
xlWorkBook = xlApp.Workbooks.Add(misValue);
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
CreateSubWorksheets();
}
public static void CreateSubWorksheets()
{
string sheetNameprefix = "SS";
Excel.Worksheet sheet1;
sheet1 = xlApp.ActiveWorkbook.Worksheets.Item["Newly Added"];
Excel.Range range = sheet1.Range["A1"].CurrentRegion;
object OriginalData = range.Value;
string OriginalAddress = range.Address;
while (range.Cells[2, 1].Value != null && range.Cells[2, 1].Value != "")
{
range.AutoFilter(1, range.Cells[2, 1].Value);
newSeet = (Excel.Worksheet)xlApp.Worksheets.Add(System.Reflection.Missing.Value,
xlWorkBook.Worksheets[xlWorkBook.Worksheets.Count],
System.Reflection.Missing.Value,
System.Reflection.Missing.Value);
//Do more stuff here
}
}
}
}
Try this...
Microsoft.Office.Interop.Excel.Application Excel = null;
Microsoft.Office.Interop.Excel._Workbook oWB = null;
Microsoft.Office.Interop.Excel._Worksheet oSheet = null;
try
{
Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();
if (xlApp == null)
{
return false;
}
Excel.Workbook xlWorkBook;
Excel.Worksheet xlWorkSheet;
object misValue = System.Reflection.Missing.Value;
xlWorkBook = xlApp.Workbooks.Add(misValue);
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.Add();
xlWorkSheet.Name = "Details";
}
I have a table of data which i need to read from excel based on user input and store it in VS as an array.
If the user enters C1, search and get the associated data:
array[0]: X1E1M101
array[1]: F2G1M202
If the user enters C2:
array[0]: X1E1M105
array[1]: F1G2M304
my data:
A B C D E
1 C1
2
3 X1 E1 M1 01
4 F2 G1 M2 02
5
6 C2
7
8 X1 E1 M1 05
9 F1 G2 M3 04
10
my code:
//I declared the Interop
using Excel = Microsoft.Office.Interop.Excel;
Excel.Application xlApp;
Excel.Workbook xlWorkBook;
Excel.Worksheet xlWorkSheet;
Excel.Range range;
xlApp = new Excel.Application();
xlWorkBook = xlApp.Workbooks.Open(ManufacturingFile);
//xlWorkSheet = ("Default Value"); // i get an error here when trying to define the worksheet name i want to select. "Cannot impicitly convert type string to ... excel.worksheet'
xlWorkSheet = ((Excel.Worksheet)this.Application.ActiveWorkbook.Sheets[1]).Select(); // This method also I get an error.
xlWorkSheet.Activate();
I am stuck after this part as I am new to using Interop.
Hope someone can help me, I am a beginner in C# and your help is much appreciated.
You will have to open your woorkbook and worksheet , there are a number of example explaining how to do that , here is a sample
Excel.Application xlApp;
Excel.Workbook xlWorkBook;
Excel.Worksheet xlWorkSheet;
Excel.Range range;
string str;
int rCnt = 0;
int cCnt = 0;
object misValue = System.Reflection.Missing.Value;
xlApp = new Excel.Application();
xlWorkBook = xlApp.Workbooks.Open("testone.xlsx", 0, true, 5, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
range = xlWorkSheet.UsedRange;
Microsoft.Office.Interop.Excel.Range xlFound =range.EntireRow.Find("C2",misValue, Excel.XlFindLookIn.xlValues, Excel.XlLookAt.xlPart,Excel.XlSearchOrder.xlByColumns,Excel.XlSearchDirection.xlNext,true, misValue, misValue);
if (!(xlFound == null))
{
int ID_Number = xlFound.Column;
int rownum = xlFound.Row;
Console.WriteLine(ID_Number);
Console.WriteLine(rownum);
Console.Read();
}
You could 1st get the range value of the search for example if 'C1' is at a1 the you will have to read the whole row from a(n+2) and stop when it finds an empty row.
Above code is not compiled its takenfrom here
If you're going to just read data from excel files I recommend you use the ExcelDataReader library instead, it offers better performance and doesn't leave ghost processes as opposed to the Interop one. Here's some sample code to set you up:
IExcelDataReader reader = null;
string FilePath = "PathToExcelFile";
//Load file into a stream
FileStream stream = File.Open(FilePath, FileMode.Open, FileAccess.Read);
//Must check file extension to adjust the reader to the excel file type
if (System.IO.Path.GetExtension(FilePath).Equals(".xls"))
{
reader = ExcelReaderFactory.CreateBinaryReader(stream);
}
else if (System.IO.Path.GetExtension(FilePath).Equals(".xlsx"))
{
reader = ExcelReaderFactory.CreateBinaryReader(stream);
}
if (reader != null)
{
//Fill DataSet
System.Data.DataSet result = reader.AsDataSet();
try
{
//Loop through rows for the desired worksheet
//In this case I use the table index "0" to pick the first worksheet in the workbook
foreach (DataRow row in result.Tables[0].Rows)
{
string FirstColumn = row[0].ToString();
}
}
catch
{
}
}
I have an Excel work book that I am adding work sheets using a loop. In the sample code below I am using a fixed array but the real code uses a database to get the names from and there can be one or many (less than 10 though).
The issue that I am having (with my code) is the worksheets get added in the reverse order of the array. So the excel sheet will open with the tabs ordered like this 1103 1102 1101 Sheet1. I know I can reorder the results from the database but that feels like a hack and I am sure there is a way to accomplish this in code. What needs to be done to set the order of tabs correctly inside my loop?
private static void SetWorksheet()
{
Excel.Application xlApp;
Excel.Workbook xlWorkBook;
Excel.Worksheet xlWorkSheet;
object misValue = System.Reflection.Missing.Value;
xlApp = new Excel.Application();
xlApp.Visible = true;
xlWorkBook = xlApp.Workbooks.Add(1);
string[] storeArray = { "1101", "1102", "1103" };
foreach (string s in storeArray)
{
xlWorkBook.Worksheets.Add();
xlWorkBook.Worksheets.Move(After: xlWorkBook.Sheets[xlWorkBook.Sheets.Count]);
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Sheets[1];
xlWorkSheet.Name = s;
releaseObject(xlWorkSheet);
}
releaseObject(xlWorkBook);
releaseObject(xlApp);
}
You can add new worksheet after the last sheet by put parameter 'After' in Add function.
xlWorkBook.Worksheets.Add(After: xlWorkBook.Sheets[xlWorkBook.Sheets.Count]);
Then you do not need to move it by using Move function.
And in the line
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Sheets[1];
It always get first sheet to change the name.
You need to change '1' to xlWorkBook.Sheets.Count
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Sheets[xlWorkBook.Sheets.Count];
Finally your code should be as below
private static void SetWorksheet()
{
Excel.Application xlApp;
Excel.Workbook xlWorkBook;
Excel.Worksheet xlWorkSheet;
object misValue = System.Reflection.Missing.Value;
xlApp = new Excel.Application();
xlApp.Visible = true;
xlWorkBook = xlApp.Workbooks.Add(1);
string[] storeArray = { "1101", "1102", "1103" };
foreach (string s in storeArray)
{
xlWorkBook.Worksheets.Add(After: xlWorkBook.Sheets[xlWorkBook.Sheets.Count]);
//xlWorkBook.ActiveSheet(After: xlWorkBook.Sheets[xlWorkBook.Sheets.Count]);
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Sheets[xlWorkBook.Sheets.Count];
xlWorkSheet.Name = s;
releaseObject(xlWorkSheet);
}
releaseObject(xlWorkBook);
releaseObject(xlApp);
}
you can add a new work sheet after 3 sheet in default in excel but you can add more then one sheet by using below code:
Microsoft.Office.Interop.Excel.Worksheet sheet1 = (Microsoft.Office.Interop.Excel.Worksheet)excelApp.Sheets.get_Item(1);
Microsoft.Office.Interop.Excel.Worksheet sheet4 = (Microsoft.Office.Interop.Excel.Worksheet)excelApp.Sheets.Add(After: wb.Sheets[3]);