Codwiz51's Wiki

RSS

Navigation







Quick Search
»
Advanced Search »
In order to write a unicode CSV file that Excel understands, the first thing you need to learn about is the Byte Order Marker (BOM). Excel uses the BOM to determine how to decode the wide character data in the file.

The other item you need to know is that Excel doesn't like to decode CSV files that contain comma separators. (Ironic, isn't it?) Excel defaults to tab characters. Your file needs to have a BOM at the beginning of the file, and your columns need to be separated by tabs.

Here is some sample code that should get you on your way with writing CSV files for Excel using unicode characters.
CString tMsg;
DWORD dwBytesWritten = 0;
LPTSTR szCSVFile = _T("C:\temp\test.csv");

// Create the CSV file
HANDLE hCSVFile = CreateFile((LPTSTR) szCSVFile, // file name
    GENERIC_READ | GENERIC_WRITE,   // open r-w
    0,      // do not share
    NULL,      // default security
    CREATE_ALWAYS,     // overwrite existing
    FILE_ATTRIBUTE_NORMAL,    // normal file
    NULL);      // no template

if (hCSVFile == INVALID_HANDLE_VALUE)
{
    tMsg.Format(_T("CreateFile failed with error %d.\n"), GetLastError());
    MessageBox((LPCTSTR)tMsg, _T("API Error"), MB_ICONSTOP);
    // Error Exit
}

// Byte Order Marker for UTF-16 Little Endian
// Note, when this is written, the output is FF FE, because Intel is
// a little endian architecture
WORD wBOM = 0xFEFF;

// Your code that loads the column names and data
// should be placed here:
// ....
// Sample header
CString strHeaderRecord(_T("ColumnText\tColumnDate\tColumnLong\tColumnDouble\r\n"));

// Some sample data
CString strDataRecord(_T("\"Some Text\"\t\"2008-12-4 18:24:33\"\t15108\t3.14159\r\n"));

// Write the BOM
if (!WriteFile(hCSVFile, &wBOM, 2, &dwBytesWritten, NULL))
{
    tMsg.Format(_T("WriteFile failed with error %d.\n"), GetLastError());
    MessageBox((LPCTSTR)tMsg, _T("API Error"), MB_ICONSTOP);
    // Error Exit
}

// Write the header
if (!WriteFile(hCSVFile, (LPCTSTR) strHeaderRecord, strHeaderRecord.GetLength() * sizeof(TCHAR), &dwBytesWritten, NULL))
{
    tMsg.Format(_T("WriteFile failed with error %d.\n"), GetLastError());
    MessageBox((LPCTSTR)tMsg, _T("API Error"), MB_ICONSTOP);
    // Error Exit
}

// Write the data
if (!WriteFile(hCSVFile, (LPCTSTR) strDataRecord, strDataRecord.GetLength() * sizeof(TCHAR), &dwBytesWritten, NULL))
{
    tMsg.Format(_T("WriteFile failed with error %d.\n"), GetLastError());
    MessageBox((LPCTSTR)tMsg, _T("API Error"), MB_ICONSTOP);
    // Error Exit

}

// Close the file handle
CloseHandle(hCSVFile);

ScrewTurn Wiki version 3.0.2.509. Some of the icons created by FamFamFam.