I have several DataTable objects and I want to write them to one excel file but various sheets.
I'm using bytescout.spreadsheet to work with excel files.
How can I write multiple table sheets to excel file using this tool and C#?
Read the manual: http://bytescout.com/products/developer/spreadsheetsdk/bytescoutxls_working_with_worksheets_in_xls_document.html
using System;
using System.Collections.Generic;
using System.Text;
using Bytescout.Spreadsheet;
namespace Worksheets
{
internal class Program
{
private static void Main(string[] args)
{
// Create new Spreadsheet
Spreadsheet document = new Spreadsheet();
// Add worksheets
Worksheet worksheet1 = document.Workbook.Worksheets.Add("Demo worksheet 1");
Worksheet worksheet2 = document.Workbook.Worksheets.Add("Demo worksheet 2");
// Get worksheet by name
Worksheet worksheetByName = document.Workbook.Worksheets.ByName("Demo worksheet 2");
// Set cell values
worksheet1.Cell(0, 0).Value = "This is Demo worksheet 1";
worksheetByName.Cell(0, 0).Value = "This is Demo worksheet 2";
// Save document
document.SaveAs("Worksheets.xls");
}
}
Related
I am using Syncfusion library to generate an excel report. I referred syncfusion to generate the report using template makers. The data is correctly exported in excel file but it is exporting NULL instead of blank string for some of nullable number columns. How can I write blank instead of NULL in excel for nullable fields.
Template file:
Output:
This is the code I am using.
using Syncfusion.XlsIO;
using (ExcelEngine excelEngine = new ExcelEngine())
{
IApplication application = excelEngine.Excel;
application.DefaultVersion = ExcelVersion.Excel2010;
IWorkbook workbook = application.Workbooks.Open(_templateFilePath);
IWorksheet worksheet = workbook.Worksheets[0];
ITemplateMarkersProcessor marker = workbook.CreateTemplateMarkersProcessor();
var data = _database.GetData();
marker.AddVariable("DATA", data);
marker.ApplyMarkers();
workbook.SaveAs(_stReportFilePath);
workbook.Close();
excelEngine.Dispose();
}
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)
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
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.
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.