output to Excel

I've been reading all the information on outputting files, however, I still cant output my array to excel. Any ideas? Please
The array call it A is A[320] with float variables. I need to ouput these to excel so i can plot a graph
Thanks
Last edited on
The simplest way would be to make a CSV file, which is just a plain-text file with each row on its own line, and each column separated by commas. Excel can read that.

Example (as a bonus you'll get to see a template function at work):
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <fstream>

// This function writes the 2D array data to file, so long as the data type is
// overloaded to work with the std::stream << operator.
// The file must already be open and ready to write.
template< typename t_data >
void write_csv( t_data *a, int nrows, int ncols, std::ostream &outs )
{
  for (int row = 0; row < nrows; row++)
  {
    for (int col = 0; col < ncols; col++)
    {
      outs << *a;
      if (col < ncols-1)
        outs << ", ";
      a++;
    }
    outs << std::endl;
  }
}

An example of using it:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>

#include "write_csv.hpp"

int main()
{
  using namespace std;

  // Here is our array. 't_data' is 'int', which works fine with <<.
  int a[ 5 ][ 10 ];

  // Lets fill our array with numbers...
  for (int row = 0; row < 5; row++)
  for (int col = 0; col < 10; col++)
    a[ row ][ col ] = (row *100) +col;

  // Print it to stdout in CSV format
  write_csv( a[0], 5, 10, cout );

  // All done!
  return EXIT_SUCCESS;
}


The trick with the a[0] is that it passes the address of the first row of the array to the function, which is an array of int (what the function takes). This relies on the fact that an array is linearly mapped (always true for every C and C++ --at least by standard).

The nice thing about a template function is that you can make arrays of int, std::string, float, char, struct, class, etc. so long as the ostream << operator is overloaded to work with it. That's true for all simple types (int, string, etc.), but not for structs and classes. You can use the same function with these different types in the same program. Mentally (or, if you just don't want to use a template function, actually) you can replace the typename t_data with whatever the base type of your array is.

Anyway, this is probably waaay more info than you wanted, but I hope you find it useful and instructive and entertaining. :-)
Crud. I just re-read your first post and realized that you are trying to output a one-dimensional array... The word 'Excel' put my brain into automatic and I thought 2D.

The concept remains the same. Just get rid of all that "row" stuff and change a[0] to a and you'll do fine.
Topic archived. No new replies allowed.