I am trying to get a form that was created in visual studio WPF C# to submit to a new excel workbook will save onto a shared network drive. I have done a bit of digging trying to find the best solution and I have came across NPOI but all of the solutions seem pretty complicated compared to what I need to do. Is there some easy resource that I can reference to simply create a workbook and insert data into specific cells -- then save?
The two related packages I have seen in NuGet are DotNetCore.NPOI and NPOI which is the one I should be using?
What I have tried so far is:
private void Button_Click(object sender, RoutedEventArgs e)
{
using (var fs = new FileStream("Result12345.xlsx", FileMode.Create, FileAccess.Write))
{
IWorkbook workbook = new XSSFWorkbook();
ISheet excelSheet = workbook.CreateSheet("Sheet1");
workbook.Write(fs);
MessageBox.Show("Form submitted successfully");
}
}
This gets outputted to : Project Folder \bin\Debug\net6.0-windows and it seems to create the workbook and save (assuming all I need to do is put in the path of the network drive in the file stream then that should be easy) but how do i insert data into cells specific cells?
I have worked with Microsoft Excel via interop COM libraries and should be directly available within your WPF app by adding as reference.
First, in the solution explorer, open the references, right-click and add reference.
Then, pick the Office libraries you are interested in working with, now or future, such as other apps too.
At the top of whatever code, you will then add the "using" clauses
using Microsoft.Office.Interop.Excel;
using System;
And here is a sample code snippet so you have control of whatever active workbook, worksheet, looping through explicit rows/columns and also getting the text of a given cell.
public void tryingExcel()
{
var SomeSampleFile = #"C:\Users\Public\SomeExcelFile.xlsx";
//Start Excel and get Application object.
var XL = new Microsoft.Office.Interop.Excel.Application();
XL.DisplayAlerts = false;
XL.Workbooks.Add();
// _Workbook and _Worksheet are part of Microsoft.Office.Interop.Excel
// via "using" clause at top of code
_Workbook wb = XL.ActiveWorkbook;
wb.Sheets.Add();
_Worksheet ws = wb.ActiveSheet;
ws.Cells[2, 1] = "Date/Time:";
ws.Cells[2, 2] = DateTime.Now;
for (var ir = 4; ir < 10; ir++)
ws.Cells[ir, 2] = "testing " + ir;;
for (var ir = 4; ir < 10; ir++)
ws.Cells[ir, 4] = ws.Cells[ir, 2].Text.Trim();
XL.ActiveWorkbook.SaveAs(SomeSampleFile, XlFileFormat.xlOpenXMLWorkbook,
Type.Missing, Type.Missing, false, false,
XlSaveAsAccessMode.xlNoChange,
XlSaveConflictResolution.xlLocalSessionChanges,
Type.Missing, Type.Missing, Type.Missing, false);
XL.Quit();
}
I have figured it out like this:
private void Button_Click(object sender, RoutedEventArgs e)
{
using (var fs = new FileStream(#"\\ipaddress\sharename\Result12345.xlsx", FileMode.Create, FileAccess.Write))
{
IWorkbook workbook = new XSSFWorkbook();
ISheet excelSheet = workbook.CreateSheet("Sheet1");
//define cell to insert into
var cellTest = excelSheet.CreateRow(0).CreateCell(0);
//set cell value
cellTest.SetCellValue("Hello?");
//save the excel sheet
workbook.Write(fs);
MessageBox.Show("Form submitted successfully");
}
}
I guess I just didn't understand why I have to create a row / cell when they already exist. Rather than setting something like Cell(0,1).value = "Something"
I have written a small code to copy few columns from source excel file to another excel file (destination excel file) using c#. Below is sample image of source excel file.
The expected result in destination excel file should be as shown in below image.
Below is my code
string fileTarget = #"C:\Users\sia\Desktop\Excel Automation\destination.xlsx";
string fileTemplate = #"C:\Users\sia\Desktop\Excel Automation\source.xlsx";
Microsoft.Office.Interop.Excel.Application excelApp = new Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel.Workbook wbTemp, wbTarget;
Microsoft.Office.Interop.Excel.Worksheet sh;
Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel.Workbook wbSource = excel.Workbooks.Open(fileTemplate, ReadOnly: false);
Microsoft.Office.Interop.Excel.Worksheet WorksheetSource = wbSource.Sheets[1];
//Copy all range in this worksheet
WorksheetSource.UsedRange.Copy(Type.Missing);
//Open destination workbook
Microsoft.Office.Interop.Excel.Workbook wbDestination = excel.Workbooks.Open(fileTarget, ReadOnly: false);
Microsoft.Office.Interop.Excel.Worksheet WorksheetDestination = wbDestination.Sheets[1];
WorksheetDestination.UsedRange.PasteSpecial(Microsoft.Office.Interop.Excel.XlPasteType.xlPasteAll, Microsoft.Office.Interop.Excel.XlPasteSpecialOperation.xlPasteSpecialOperationNone, Type.Missing, Type.Missing);
wbDestination.SaveAs(#"C:\Users\sia\Desktop\Excel Automation\destination.xlsx");
wbSource.Close();
excel.Quit();
System.Runtime.InteropServices.Marshal.ReleaseComObject(excel);
But the i'm not getting the expected format, below is the result I'm getting.
where and what modification i need to do in my existing code to get the expected result.
Thanks
You need to specify proper column and range, otherwise by default paste will go in the first column
workSheet.Range
For reference: Copy/paste cells in Excel with C#
How do I convert a particular sheet to CSV from Excel using C# Interop? Does it default to the first sheet or can I specify?
This is the code i am using:
private void ConvertProgsToCSV()
{
Excel.Application app = new Excel.Application();
Excel.Workbook wb = app.Workbooks.Open(txtFname.Text);
wb.SaveAs(#"C:\Temp\output.csv", Excel.XlFileFormat.xlCSVWindows);
wb.Close(false);
app.Quit();
Console.WriteLine("Done!");
}
You have to open worksheet by it's name and Select it using Select() function:
xlSheet = (Excel.Worksheet)xlBook.Worksheets["Sheet1"];
xlSheet.Select(Type.Missing);
xlBook.SaveAs("C:\Filename.csv", Excel.XlFileFormat.xlCSV,Excel.XlSaveAsAccessMode.xlNoChange);
Assuming that xlSheet is of typeInterop.Excel.WorkSheet and xlBook is of type Interop.Excel.Workbook
You can refer to this links for more info:
How to: Programmatically Select Worksheets
Working with Worksheets
C# with Excel -- How to select a sheet?
I have a .txt file that is already in Comma-separated values (csv) format.
I want to add the data in the .txt file as a sheet to an open Excel workbook.
this is how I open the workbook:
var xlApp = new Excel.Application { Visible = false };
Excel.Workbook newWorkbook = xlApp.Workbooks.Add(Type.Missing);
And this is how I try to add the .txt file to the workbook:
string txt2xls = Globals.HomeDir + "\\JSL\\Data1" + ".txt";
string csv2xls = Globals.HomeDir + "\\JSL\\Data1" + ".csv";
if (File.Exists(csv2xls))
File.Delete(csv2xls);
File.Move(txt2xls, Path.ChangeExtension(txt2xls, ".csv"));
newWorkbook.Sheets.Add(csv2xls, Type.Missing, Type.Missing, Type.Missing);
The last line gave me an error (HRESULT: 0x800A03EC).
What can i do to solved this problem?
thanks!
CSV file in Excel can have allways only one worksheet. You cannot add another sheet as CSV. You will have to open the CSV separately as another Workbook and copy the Worksheet from that Workbook to your multi-sheet xlsx Workbook newWorkbook.
Use Worksheet.Copy method as described in How to: Programmatically Copy Worksheets and here.
var xlApp = new Excel.Application { Visible = false };
Excel.Workbook newWorkbook = xlApp.Workbooks.Add(Type.Missing);
Excel.Workbook csvWorkbook = xlApp.Workbooks.Open(csv2xls);
Excel.Worksheet worksheetCSV = ((Excel.Worksheet)csvWorkbook.Worksheets[1]);
Excel.Worksheet targetWorksheet = ((Excel.Worksheet)newWorkbook.Worksheets[1]);
worksheetCSV.Copy(targetWorksheet);
Also mark that
If you do not specify either Before or After, Microsoft Office Excel
creates a new workbook that contains the copied sheet.
So you can do
worksheetCSV.Copy(Type.Missing, Type.Missing);
and no need to explitly Add newWorkbook.
I am trying to convert some VBA code to C#. I am new to C#. Currently I am trying to open an Excel file from a folder and if it does not exist then create it. I am trying something like the following. How can I make it work?
Excel.Application objexcel;
Excel.Workbook wbexcel;
bool wbexists;
Excel.Worksheet objsht;
Excel.Range objrange;
objexcel = new Excel.Application();
if (Directory("C:\\csharp\\error report1.xls") = "")
{
wbexcel.NewSheet();
}
else
{
wbexcel.Open("C:\\csharp\\error report1.xls");
objsht = ("sheet1");
}
objsht.Activate();
You need to have installed Microsoft Visual Studio Tools for Office (VSTO).
VSTO can be selected in the Visual Studio installer under Workloads > Web & Cloud > Office/SharePoint Development.
After that create a generic .NET project and add a reference to Microsoft.Office.Interop.Excel via 'Add Reference... > Assemblies' dialog.
Application excel = new Application();
Workbook wb = excel.Workbooks.Open(path);
Missing.Value is a special reflection struct for unnecessary parameters replacement
In newer versions, the assembly reference required is called Microsoft Excel 16.0 Object Library. If you do not have the latest version installed you might have Microsoft Excel 15.0 Object Library, or an older version, but it is the same process to include.
FileInfo fi = new FileInfo("C:\\test\\report.xlsx");
if(fi.Exists)
{
System.Diagnostics.Process.Start(#"C:\test\report.xlsx");
}
else
{
//file doesn't exist
}
private void btnChoose2_Click(object sender, EventArgs e)
{
OpenFileDialog openfileDialog1 = new OpenFileDialog();
if (openfileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
this.btnChoose2.Text = openfileDialog1.FileName;
String filename = DialogResult.ToString();
var excelApp = new Excel.Application();
excelApp.Visible = true;
excelApp.Workbooks.Open(btnChoose2.Text);
}
}
Imports
using Excel= Microsoft.Office.Interop.Excel;
using Microsoft.VisualStudio.Tools.Applications.Runtime;
Here is the code to open an excel sheet using C#.
Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel.Workbook wbv = excel.Workbooks.Open("C:\\YourExcelSheet.xlsx");
Microsoft.Office.Interop.Excel.Worksheet wx = excel.ActiveSheet as Microsoft.Office.Interop.Excel.Worksheet;
wbv.Close(true, Type.Missing, Type.Missing);
excel.Quit();
Here is a video mate on how to open an excel worksheet using C# https://www.youtube.com/watch?v=O5Dnv0tfGv4
For opening a file, try this:
objexcel.Workbooks.Open(#"C:\YourPath\YourExcelFile.xls",
missing, missing, missing, missing, missing, missing, missing,
missing, missing, missing, missing, missing,missing, missing);
You must supply those stupid looking 'missing' arguments. If you were writing the same code in VB.Net you wouldn't have needed them, but you can't avoid them in C#.
you should open like this
Excel.Application xlApp ;
Excel.Workbook xlWorkBook ;
Excel.Worksheet xlWorkSheet ;
object misValue = System.Reflection.Missing.Value;
xlApp = new Excel.ApplicationClass();
xlWorkBook = xlApp.Workbooks.Open("csharp.net-informations.xls", 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);
source : http://csharp.net-informations.com/excel/csharp-open-excel.htm
ruden
It's easier to help you if you say what's wrong as well, or what fails when you run it.
But from a quick glance you've confused a few things.
The following doesn't work because of a couple of issues.
if (Directory("C:\\csharp\\error report1.xls") = "")
What you are trying to do is creating a new Directory object that should point to a file and then check if there was any errors.
What you are actually doing is trying to call a function named Directory() and then assign a string to the result. This won't work since 1/ you don't have a function named Directory(string str) and you cannot assign to the result from a function (you can only assign a value to a variable).
What you should do (for this line at least) is the following
FileInfo fi = new FileInfo("C:\\csharp\\error report1.xls");
if(!fi.Exists)
{
// Create the xl file here
}
else
{
// Open file here
}
As to why the Excel code doesn't work, you have to check the documentation for the Excel library which google should be able to provide for you.
Microsoft.Office.Interop.Excel.Application excapp;
excapp = new Microsoft.Office.Interop.Excel.Application();
object misval=System.Reflection.Missing.Value;
Workbook wrkbuk = new Workbook();
Worksheet wrksht = new Worksheet();
wrkbuk = excapp.Workbooks._Open(#"C:\Users\...\..._template_v1.0.xlsx", misval, misval,
misval, misval, misval, misval, misval, misval, misval, misval, misval, misval);
wrksht = (Microsoft.Office.Interop.Excel.Worksheet)wrkbuk.Worksheets.get_Item(2);
Is this a commercial application or some hobbyist / open source software?
I'm asking this because in my experience, all free .NET Excel handling alternatives have serious problems, for different reasons. For hobbyist things, I usually end up porting jExcelApi from Java to C# and using it.
But if this is a commercial application, you would be better off by purchasing a third party library, like Aspose.Cells. Believe me, it totally worths it as it saves a lot of time and time ain't free.
Code :
private void button1_Click(object sender, EventArgs e)
{
textBox1.Enabled=false;
OpenFileDialog ofd = new OpenFileDialog();
ofd.Filter = "Excell File |*.xlsx;*,xlsx";
if (ofd.ShowDialog() == DialogResult.OK)
{
string extn = Path.GetExtension(ofd.FileName);
if (extn.Equals(".xls") || extn.Equals(".xlsx"))
{
filename = ofd.FileName;
if (filename != "")
{
try
{
string excelfilename = Path.GetFileName(filename);
}
catch (Exception ew)
{
MessageBox.Show("Errror:" + ew.ToString());
}
}
}
}
For editing Excel files from within a C# application, I recently started using NPOI.
I'm very satisfied with it.