I tried searching for examples and never i found an example for inserting data into an empty excel.
Insert into [Sheet1$] (columnname1, columnName2) values ("somevalue","somevalue");
If I understand correctly, you want a simple way to create a file that can be read in excel. The simple solution I use many times, when I don't need any advanced features of excel sheets, is a CSV (comma seperated value).
You format your data like this :
COLUMN1,COLUMN2,COLUMN3
ROW1_VALUE1,ROW1_VALUE2,ROW1_VALUE3
ROW2_VALUE1,ROW2_VALUE2,ROW2_VALUE3
Between the lines there are linebreaks. On Windows use \r\n.
You can construct the file any way that you wish, for example :
File.WriteAllText("test.csv","product,price\r\nbook,100\r\ncoffee,500");
This will produce a CSV that can be read in excel.
Excel.Worksheet oSheet;
//------
oSheet.Cells[Row,Column] = "Some Info";
// --- Row & Column starts with 1
Related
I am trying to build simple program that does my weekly job.
Everytime I receive csv file, I maintain excel file.
My csv is like below:
key_code,eng_name,...so on
000001,some name,...so on
My excel is like below:
Some text are written on A1-G4
No column hearders written
Data is from 5th row
Each row has data from B-G(1st row B5-G5, 2nd row B6-G6)
If key_code in csv does not exist in excel, I add.
If key_code in csv does exist in excel, I update the rest columns.
If key_code in excel does not exist in csv, I delete the row.
Can anyone tell me any easy way or steps to get this done?
I am very confusing about what to use to update excel file among OleDb, Interop.Excel, epplus, spire.xls, etc.
And in which class do I have to store csv data and excel data to compare.
For reading CSV you can use ChoETL reader, this is one of the best CSV readers I have ever used.
The tricky part is to how to write Excel file and choosing the right tool, amongst the tools you have mentioned EPPlus is best because
Excel.Interop needs Excel(MS Office) to be installed on production machine which can create licencing issues
To use OleDB you need some nitty gritty to use it a better way
EPPlus provides some abstraction which makes it easy to manipulate the excel files
using (var p = new ExcelPackage())
{
//A workbook must have at least on cell, so lets add one...
var ws=p.Workbook.Worksheets.Add("MySheet");
//To set values in the spreadsheet use the Cells indexer.
ws.Cells["A1"].Value = "This is cell A1";
//Save the new workbook. We haven't specified the filename so use the Save as method.
p.SaveAs(new FileInfo(#"c:\workbooks\myworkbook.xlsx"));
}
This is very simple example given on the github page to write, please use it and post any specific issues
If key_code in csv does not exist in excel, I add.
If key_code in csv does exist in excel, I update the rest columns.
If key_code in excel does not exist in csv, I delete the row.
As my understanding of the rules above, you simply delete the old excel file and create a new file from the data in the CSV file.
You can use R to do this very easily:
#Install package 'writexl' if you didn't, by install.packages("writexl")
library(writexl)
#File excel
fn <- "file.xlsx"
#Check its existence
if (file.exists(fn))
#Delete file if it exists
file.remove(fn)
#Read the csv file to a data frame
df <- read.csv("C:/newfile.csv")
#Write the data frame to excel file. Change col_names = TRUE if you want the headers.
write_xlsx(
df,
path = "file.xlsx",
col_names = FALSE
)
I need to take values form one sheet in one Excel workbook and insert them into another existing workbook.
The values I need to take are the first 6 columns of the first file:
And I want to insert them at the beginning of another book like so
I've been using Spire.Xls to read values from the first sheet and I thought I could just do the same; parse the worksheet, read the values and just paste them into the other sheet, but that wouldn't work because three of the columns I want to copy have the same header "Descripcion" so my parser would only take the values form the first descripcion column and skip the other ones.
Is there any way, using Excel.Interop or maybe Spire itself to copy and paste entire columns between workbooks? Or alternately, is there any way to get all of the 3 "descripcion" values (without rewriting the title of the columns)?
VSTO might be helpful. I've done similar tasks in C#/VSTO.
Perhaps read through: Simple Example of VSTO Excel using a worksheet as a datasource
I would like to output a table to a webpage. The table is stored in an excel sheet (xls).
Is it possible to use xslt for this? The table is the cells are in this range:
A26 - P36 (16 columns and 11 rows)
If an exmaple file is need here is a link:
http://finans.opengate.dk/media/6704/2010-01-13.xls
Update: A daily file is uploaded. And I would like to automatically show a table from the latest xls-file using xslt. If some C# is needed to convert it from excel to something else (XML?) that is fine. It is done in the CMS Umbraco and that is why I hope to use XSLT since that is the way to show things in Umbraco, through xslt makroes.
BR. Anders
UPDATE with answer (based on answers below): No, it is not possible to read xls-files using xslt. If needed then one has to save excel sheet in another format xml or html. Or one will need a real programming language to read the excel file.
XSLT is mostly used to convert XML from one dialect to another, not to convert xls files to html.
If you just want to do this manually, you can save your worksheet as HTML directly in excel.
It is not clear from your question if you want to do this programmatically, and if so using what programming language.
You can use ADO.net to access cells in an excel file, similar to a DB query. This is a bit lighter than trying to use Excel automation objects.
http://support.microsoft.com/kb/316934
SpreadsheetGear for .NET can read Excel files and display them in a DataGrid as shown in the Excel to DataGrid sample on this page:
// Create a workbook from an Excel file
String ssFile = Server.MapPath("files/spiceorder.xls");
SpreadsheetGear.IWorkbook workbook = SpreadsheetGear.Factory.GetWorkbook(ssFile);
// Get a DataSet from an existing defined name
DataSet dataSet = workbook.GetDataSet("orderrange", SpreadsheetGear.Data.GetDataFlags.FormattedText);
// Bind a DataGrid to the DataSet
DataGrid1.DataSource = dataSet;
DataGrid1.DataBind();
SpreadsheetGear can also render png/gif/jpg images from cell ranges or charts as demonstrated here.
You can download the free trial here if you want to try it yourself.
Disclaimer: I own SpreadsheetGear LLC
I am using oledb to read data from an excel file and store it in a dataset.
My excel file contents are like as follows:
0 0 somestring somestring
500 200 somestring somestring
When i checked the contents of my data set, the values of Columns 1 & 2 are not stored as integers but rather as DateTime values.
How will I make it be stored as integer values instead of DateTime?
Have you tried adding IMEX=1 to your OLEDB connection string?
Are you sure its a number? Following could be a few options:
Right click the columns in excel and change the format to Text/Custom.
Look into the NamedRange.FormatConditions Property; change the format the data when you read it from excel, see MSDN
Or try deleting an existing format on a range:
that is,
Excel.Worksheet sheet = this.Application.ActiveSheet as Excel.Worksheet;
Excel.Range range = sheet.get_Range("A1", "A5") as Excel.Range;
//delete previous validation rules
range.Validation.Delete();
You could use a 3rd party component like SpreadsheetGear for .NET which lets you get the underlying values of cells (with IWorkbook.Worksheets["MySheet"].Cells[rowIndex, colIndex].Value) regardless of the cell format, or you can get the formatted result with IRange.Text.
You can see live ASP.NET samples here and download the free trial here.
Disclaimer: I won SpreadsheetGear LLC
How do I import data in Excel from a CSV file using C#? Actually, what I want to achieve is similar to what we do in Excel, you go to the Data tab and then select From Text option and then use the Text to columns option and select CSV and it does the magic, and all that stuff. I want to automate it.
If you could head me in the right direction, I'll really appreciate that.
EDIT: I guess I didn't explained well. What I want to do is something like
Excel.Application excelApp;
Excel.Workbook excelWorkbook;
// open excel
excelApp = new Excel.Application();
// something like
excelWorkbook.ImportFromTextFile(); // is what I need
I want to import that data into Excel, not my own application. As far as I know, I don't think I would have to parse the CSV myself and then insert them in Excel. Excel does that for us. I simply need to know how to automate that process.
I think you're over complicating things. Excel automatically splits data into columns by comma delimiters if it's a CSV file. So all you should need to do is ensure your extension is CSV.
I just tried opening a file quick in Excel and it works fine. So what you really need is just to call Workbook.Open() with a file with a CSV extension.
You could open Excel, start recording a macro, do what you want, then see what the macro recorded. That should tell you what objects to use and how to use them.
I beleive there are two parts, one is the split operation for the csv that the other responder has already picked up on, which I don't think is essential but I'll include anyways. And the big one is the writing to the excel file, which I was able to get working, but under specific circumstances and it was a pain to accomplish.
CSV is pretty simple, you can do a string.split on a comma seperator if you want. However, this method is horribly broken, albeit I'll admit I've used it myself, mainly because I also have control over the source data, and know that no quotes or escape characters will ever appear. I've included a link to an article on proper csv parsing, however, I have never tested the source or fully audited the code myself. I have used other code by the same author with success. http://www.boyet.com/articles/csvparser.html
The second part is alot more complex, and was a huge pain for me. The approach I took was to use the jet driver to treat the excel file like a database, and then run SQL queries against it. There are a few limitations, which may cause this to not fit you're goal. I was looking to use prebuilt excel file templates to basically display data and some preset functions and graphs. To accomplish this I have several tabs of report data, and one tab which is raw_data. My program writes to the raw_data tab, and all the other tabs calculations point to cells in this table. I'll go into some of the reasoning for this behavior after the code:
First off, the imports (not all may be required, this is pulled from a larger class file and I didn't properly comment what was for what):
using System.IO;
using System.Diagnostics;
using System.Data.Common;
using System.Globalization;
Next we need to define the connection string, my class already has a FileInfo reference at this point to the file I want to use, so that's what I pass on. It's possible to search on google what all the parameters are for, but basicaly use the Jet Driver (should be available on ANY windows install) to open an excel file like you're referring to a database.
string connectString = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source={filename};Extended Properties=""Excel 8.0;HDR=YES;IMEX=0""";
connectString = connectString.Replace("{filename}", fi.FullName);
Now let's open up the connection to the DB, and be ready to run commands on the DB:
DbProviderFactory factory = DbProviderFactories.GetFactory("System.Data.OleDb");
using (DbConnection connection = factory.CreateConnection())
{
connection.ConnectionString = connectString;
using (DbCommand command = connection.CreateCommand())
{
connection.Open();
Next we need the actual logic for DB insertion. So basically throw queries into a loop or whatever you're logic is, and insert the data row-by-row.
string query = "INSERT INTO [raw_aaa$] (correlationid, ipaddr, somenum) VALUES (\"abcdef", \"1.1.1.1", 10)";
command.CommandText = query;
command.ExecuteNonQuery();
Now here's the really annoying part, the excel driver tries to detect you're column type before insert, so even if you pass a proper integer value, if excel thinks the column type is text, it will insert all you're numbers as text, and it's very hard to get this treated like a number. As such, excel must already have the column type as the number. In order to accomplish this, for my template file I fill in the first 10 rows with dummy data, so that when you load the file in the jet driver, it can detect the proper types and use them. Then all my forumals that point at my csv table will operate properly since the values are of the right type. This may work for you if you're goals are similar to mine, and to use templates that already point to this data (just start at row 10 instead of row 2).
Because of this, my raw_aaa tab in excel might look something like this:
correlationid ipaddr somenum
abcdef 1.1.1.1 5
abcdef 1.1.1.1 5
abcdef 1.1.1.1 5
abcdef 1.1.1.1 5
abcdef 1.1.1.1 5
abcdef 1.1.1.1 5
abcdef 1.1.1.1 5
abcdef 1.1.1.1 5
Note row 1 is the column names that I referenced in my sql queries. I think you can do without this, but that will require a little more research. By already having this data in the excel file, the somenum column will be detected as a number, and any data inserted will be properly treated as such.
Antoher note that makes this annoying, the Jet Driver is 32-bit only, so in my case where I had an explicit 64-bit program, I was unable to execute this directly. So I had the nasty hack of writing to a file, then launch a program that would insert the data in the file into my excel template.
All in all, I think the solution is pretty nasty, but thus far haven't found a better way to do this unfortunatly. Good luck!
You can take a look at TakeIo.Spreadsheet .NET library. It accepts files from Excel 97-2003, Excel 2007 and newer, and CSV format (semicolon or comma separators).
Example:
var inputFile = new FileInfo("Book1.csv"); // could be .xls or .xlsx too
var sheet = Spreadsheet.Read(inputFile);
foreach (var row in sheet)
{
foreach (var cell in row)
{
// do something
}
}
You can remove beginning and trailing empty rows, and also beginning and trailing columns from the imported data using the Normalize() function:
sheet.Normalize();
Sometimes you can find that your imported data contains empty rows between data, so you can use another helper for this case:
sheet.RemoveEmptyRows();
There is a Serialize() function to convert any input to CSV too:
var outfile = new StreamWriter("AllData.csv");
sheet.Serialize(outfile);
If you like to use comma instead of the default semicolon separator in your CSV file, do:
sheet.Serialize(outfile, ',');
And yes, there is also a ToString() function too...
This package is available at NuGet too, just take a look at TakeIo.Spreadsheet.
You can use ADO.NET
http://vbadud.blogspot.com/2008/09/opening-comma-separate-file-csv-through.html
Well, importing from CSV shouldn't be a big deal. I think the most basic method would be to do it using string operations. You could build a pretty fine parser using simple Split() command, and getting the stuff in arrays.