开发者

C# converting .xls to .csv without Excel [duplicate]

开发者 https://www.devze.com 2023-04-08 15:06 出处:网络
This question already has answers here: Is there any simple way to convert .xls file to .csv file? (Excel)
This question already has answers here: Is there any simple way to convert .xls file to .csv file? (Excel) (9 answers) Closed 10 years ago.

开发者_高级运维Need to convert a .xls or .xlsx to a .csv without the use of Excel in an C#/ASP.net web app. The application is currently using the NPOI.dll for some functionality but I do not see any info on the codeplex wiki for NPOI for that particular functionality. Does anyone have any suggestions?

Thanks


There are libraries ( Excel Data Reader, for eg) that let you read excel. Once you are able to read data, writing to csv should be simple.


ADODB.NET can be used to treat the Excel files as datasource.

//string ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties=Excel 8.0;";
string ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=Excel 12.0;";

ConnectionString = string.Format(ConnectionString, @"FullPathToExcelFile");

OleDbConnection conn = new OleDbConnection(ConnectionString);
conn.Open();

OleDbCommand cmdSelect = new OleDbCommand("SELECT * FROM [Sheet1$]", conn);
OleDbDataAdapter oleDBAdapter = new OleDbDataAdapter();
oleDBAdapter.SelectCommand = cmdSelect;

DataSet myDataset = new DataSet();
oleDBAdapter.Fill(myDataset);
conn.Close(); 

// Do whatever with data in myDataset including export to csv...


Have a look at the FileHelpers library. It will do exactly what you want.

With FileHelpers, you can read from Excel files and write to csv or flat text files. And it's object oriented! All you have to do is to annotate classes with some attributes so that they match the source excel file.

Consider this example:

[DelimitedRecord("|")]
public class CustomersVerticalBar {
   public string CustomerID;
   public string CompanyName;
   ...
}

Read using this:

ExcelStorage provider = new ExcelStorage(typeof(CustomersVerticalBar));

provider.StartRow = 3;
provider.StartColumn = 2;

provider.FileName = "Customers.xls";

CustomerVerticalBar[] res = (CustomerVerticalBar[]) provider.ExtractRecords();

Example taken from here: http://filehelpers.sourceforge.net/example_exceldatalink.html


.xls is a proprietary binary format which cannot be read in plain text format, so you will need office or Libre Office or something to read that... .xlsx is an xml based format, and should be possible just by parsing through the DOM... but you would still be manually iterating through each value and manually delimiting, etc. Have you considered using an xslt?

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号