Is there a quick way to export an array to an Excel file using C #?

I have point arrays that contain raw data (x and y). Is there a quick way to output these arrays to an excel file?

thanks

+6
c # excel
source share
5 answers

Output data to a file, separating the elements of the array with commas. Then save the file as name.csv

Use FileWriter to output the file.

+9
source share

One of these nice things about the range object is that you can assign a two-dimensional array directly to the value property. It is important that the range be the same number of cells as the array.

//using Excel = Microsoft.Office.Interop.Excel; String[,] myArr = new string[10, 10]; for (int x = 0; x < 10; x++) { for (int y = 0; y < 10; y++) { myArr[x, y] = "Test " + y.ToString() + x.ToString(); } } Excel.Application xlApp = new Excel.Application(); xlApp.Visible = true; Excel.Workbook wb = xlApp.Workbooks.Add(Excel.XlWBATemplate.xlWBATWorksheet); Excel.Worksheet ws = (Excel.Worksheet)wb.Worksheets.get_Item(1); Excel.Range rng = ws.Cells.get_Resize(myArr.GetLength(0), myArr.GetLength(1)); rng.Value2 = myArr; 
+8
source share

If CSV is not satisfactory, you can use Microsoft.Office.Interop.Excel. Example: A practical guide. Using COM Interop to Create an Excel Spreadsheet (C # Programming Guide) .

+4
source share

I would use a third-party xsl export component. This will save you the frills of excel automation and you don’t have to associate excel interop assemblies with your application.

MyXls is a simple, open source component that outperforms exports. It should fully satisfy your needs.

+2
source share

You can do this using Ado.net. My code below assumes that there is an Excel1.xls table in the C: \ Stuff \ folder, and the distribution table has a header identifier, name, site that is already in the sheet named Sheet1.

 private void button1_Click(object sender, EventArgs e) { string connectionString = @"Provider=Microsoft.Jet.OLEDB.4.0; Data Source=C:\Stuff\Book1.xls;Extended Properties= ""Excel 8.0;HDR=YES;"""; using (OleDbConnection conn = new OleDbConnection(connectionString)) { using (OleDbCommand command = conn.CreateCommand()) { command.CommandText = @"INSERT INTO [Sheet1$] (ID, Name, Site) VALUES(1, ""Phil"", ""StackOverflow.com"")"; conn.Open(); command.ExecuteNonQuery(); } } } 
+2
source share

All Articles