I'm working in VS2005 and I need the C# syntax write to write collection values in an Excel sheet. I initialize the collection like this:
Reports oReports =new Reports();//oReports is a collection
Assuming that this collection has values, how would I write them to Excel?
You could do something quick and dirty if you don't want to faff around learning how to write to Excel - just write out to a .csv file, open it yourself in excel and save as Excel format.
Just output in a stream, such as: (will work if your report values have commas in them too)
using (StreamWriter sw = new StreamWriter(#"C:\file.csv"))
{
StringBuilder csvLine = new StringBuilder();
//Enter your header row here:
csvLine.Append("Header1,Header2,Header3");
sw.WriteLine(csvLine.ToString());
foreach (Report report in Reports)
{
csvLine = new StringBuilder();
csvLine.Append(string.Format("\"{0}\",", report.Value1));
csvLine.Append(string.Format("\"{0}\",", report.Value2));
csvLine.Append(string.Format("\"{0}\"", report.Value3)); //etc
sw.WriteLine(csvLine.ToString());
}
sw.Flush();
}
Loop through the collection and add the collection values to cells in your spreadsheet.
Here's a couple links on how to work with an excel spreadsheet in .Net
http://www.c-sharpcorner.com/UploadFile/thiagu304/ExcelAutomation01052007080910AM/ExcelAutomation.aspx
http://support.microsoft.com/default.aspx?scid=kb;EN-US;302084
Convert your reports to an object array (two dimensional), and assign the array to an excel range
Related
I am trying to count the number of sheets in a workbook. The workbook is created using NPOI and there doesn't seem to be a way to count the amount of sheets using the C# version of NPOI?
This is a really tricky thing to both explain and show... But I will give it a try.
What I am trying to do is having an existing excel-file as a template for statistics. This existing excel-file can have different amounts of templates and I need to be able to count these templates to know where to place my new sheets and edit their names.
The sender of the data only has to chose which template-sheet should be filled with which data, and I will then remove the template-sheets from the workbook after all data has been inserted.
What I have tried:
I have read the documentation and searched for information and have tried the following approaches:
getNumberOfSheets - How to know number of sheets in a workbook?
Problem with this approach: The C# version of NPOI doesn't seem to have getNumberOfSheets.
Convert found row-counters into sheet-counters - NPOI - Get excel row count to check if it is empty
Can't really recreate the code to work for sheets as the functionality for sheets and rows are too different.
var sheetIndex = 0;
foreach (var sheet in requestBody.Sheets)
{
if (sheet.TemplateNumber == "")
{
sheetTemplate = templateWorkbook.CreateSheet(sheet.Name);
}
else
{
sheetTemplate = templateWorkbook.CloneSheet(Convert.ToInt32(sheet.SheetTemplate));
if (!templates.Contains(Convert.ToInt32(sheet.SheetTemplate)))
{
templates.Add(Convert.ToInt32(sheet.SheetTemplate));
}
// Do math's to make sure we add the name to the newly created sheet further down the code (I need to actual index here)
}
// Insert statistics
//After inserting statistics:
workingCopy.SetSheetName(sheetIndex, sheet.Name);
foreach (var template in templates)
{
workingCopy.RemoveSheetAt(template);
}
}
You can get number of sheets from NumberOfSheets property in XSSFWorkbook class.
I'm creating an Excel file using the EPPlus library and C#.
In this Excel file there is a sheet with pivot table to which I'd like to add a filter field like in this manually created Excel sheet (Country):
How can I do this using EPPlus?
I did not see your code, but you can do something like this.
var ws = excelPackage.Workbook.Worksheets["index of your worksheet"];
var pivotTable = ws.PivotTables[0]; //assuming that you only have 1
var pivotField = pivotTable.Fields["Country"];
pivotTable.PageFields.Add(pivotField); // should add field into desired place
Hope it´s a little bit helpful. Don´t forget to save your excel file at the end.
So I have a HUGE excel file with headers, names, values stored.
I'm wanting to read everhting from row 5-95 and column A,B,C,D. I dont want to use a database I want to use a list or array.
What would be a way to read in the excel file and get the info I want?
You can use EasyXLS Excel library.
For reading XLS files use this code:
ExcelDocument xls = new ExcelDocument();
List listRows = xls.easy_ReadXLSSheet_AsList("file.xls", "SheetName", "A5:D95")
For reading XLSX files use this code:
ExcelDocument xls = new ExcelDocument();
List listRows = xls.easy_ReadXLSXSheet_AsList("file.xlsx", "SheetName", "A5:D95")
The listRows will containg the rows and each of this rows is another list that contains the cell values.
I need to import data from 50 similar csv files to a single excel sheet.
Is there any way to get only selected columns from each file and put them together in one sheet.
Structure of my csv files: A few columns exactly same in all the files. (I want them to be in excel) then one column with same column name but different data which I want to place next to each other with different names in the excel sheet. I do not not want all other remaining columns from csv files.
In short,
read all csv files,
get all the columns which are common to all csv & put in excel sheet.
Now, take one column from each file which has the same header but different data and put one after the other in excel sheet with named from the csv file name.
Leave remaining rest of the columns.
Write excel sheet to a excel file.
Initially I thought it can be easily done, but considering my programming skill in learning stage it is way difficult for me. Please help.
Microsoft Text Driver allows you to read CSV data in a DataSet, making data manipulation easy.
This Stack Overflow question is a good starting point.
Fastest way could be using FileHelpers to read CSV into a DataTable :
http://filehelpers.sourceforge.net/FileHelpers.CommonEngine.CsvToDataTable_overload_4.html
and then with EPPlus export that DataTable in excel, use method DataTableToExcelXlsx from this snippet:
https://stackoverflow.com/a/9569827/351383
With EPPlus you don't have to have Excel installed on machine that is executing this code, and you can use it on server (ASP.NET)
With a very simple coding, I was able to read the files. Now, the only thing we need to do is to make this code a bit fancy to loop thorough all the CSV files in the folder given and collect data. Once we read the data, it can be filtered and put to an excel as we want.
Of course, excel can import CSV itself, but it is not that practical to do this every time. And again we can add the code to application to use in flexibility, exactly what I am trying to do.
public static System.Data.DataTable GetDataTable(string strFileName)
{
System.Data.OleDb.OleDbConnection dbConnect = new System.Data.OleDb.OleDbConnection("Provider=Microsoft.Jet.OleDb.4.0; Data Source = " + System.IO.Path.GetDirectoryName(strFileName) + ";Extended Properties = \"Text;HDR=YES;FMT=TabDelimited\"");
dbConnect.Open();
string strQuery = "SELECT * FROM [" + System.IO.Path.GetFileName(strFileName) + "]";
System.Data.OleDb.OleDbDataAdapter adapter = new System.Data.OleDb.OleDbDataAdapter(strQuery, dbConnect);
System.Data.DataSet dSet = new System.Data.DataSet("CSV File");
adapter.Fill(dSet);
dbConnect.Close();
return dSet.dbTables[0];
}
I am working on a project which involves getting data from a .doc or a .docx file. The input requirements are in a tabular format. Is it possible to retrieve data from table in a row wise manner or as a dataset.I am using Microsoft.Office.Interop.Word to get the data from the doc file.
You can use the property Tables of the Document interface to get a collection with all the tables in your document. For each Table in this collection you can get the rows and for each row the cells.
I.e. if app is your Application object you can write something like this to get the text contained in each cell(supposing that there is exactly one in your doc):
string aCellText;
foreach (Row aRow in Application.ActiveDocument.Tables[0].Rows)
foreach (Cell aCell in aRow.Cells)
aCellText = aCell.Range.Text;
That is not possible with the word, but if you want something like that than you should put tabular data in you excel file and than you can easily read it in the dataset object....
this is not possible to get the data in dataset object from .doc or .docx file. But if your data is in tabular form and also in the excel sheet than you can retrieve the data in dataset object. MS Word is for documentation purpose and excel is used for maintaining data sheets..