/*------------------------------------------------------------------------------*
 * File Name:				 													*
 * Creation: 																	*
 * Purpose: OriginC Source C file associated with MultipleWorksheet.OIF filter	*
 * Copyright (c) OriginLab Corp. 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010	*
 * All Rights Reserved															*
 * 																				*
 * Modification Log:															*
 *------------------------------------------------------------------------------*/
 

#include <Origin.h>
#include <..\Originlab\fileimport.h>

// This function will be called by import wizard for the Excel file with multiple
// worksheets. This function uses COM to extract each worksheet from the Excel
// workbook to a separate temporary disk ASCII file, and then each ASCII file is
// imported using the ImpWiz code, with a special single worksheet filter file.
//

int MultipleWorksheets(Page& pgTarget, TreeNode& trFilter, LPCSTR lpcszFile, int nFile)	
{
	// Declare Excel objects
	Object	oExcel, oExcelWkbks, oExcelWkbk, oExcelWksh;
	
	// Create an Excel application object and set it as invisible
	oExcel = CreateObject("excel.application");
	oExcel.Visible = false;
	
	// Get the workbooks collection of the Excel object
	oExcelWkbks = oExcel.Workbooks;
	
	// Open the workbook with data to be analyzed
	oExcelWkbk = oExcelWkbks.Open(lpcszFile);

	// turn off Excel messages
	oExcel.DisplayAlerts = FALSE;
	
	// Loop over each worksheet in the Excel workbook and write them out to a file
	StringArray saFileNames;	
	string strSingleFile;
	foreach (oExcelWksh in oExcelWkbk.Worksheets)
	{
		// Get name for windows temp file
		get_temp_file_name(strSingleFile);
		// Save current worksheet to temp file, as tab-delimited ASCII
		DWORD dwFileFormat = 20;
		oExcelWksh.SaveAs(Filename:=strSingleFile, FileFormat:= dwFileFormat);
		// Store file name in array
		saFileNames.Add(strSingleFile);
	}
	// Close Excel application
	oExcel.Quit();	

	// Now loop over all ASCII files that were created, and import them one at a time
	string strSingleFilter = LabTalk.System.Path.Program$ + "Samples\\Programming\\User-Defined Import\\SingleWorksheet.oif";
	for(int ii=0; ii < saFileNames.GetSize(); ii++)
	{
		// Call Import function
		int iRet = ImportFile(pgTarget, strSingleFilter, saFileNames[ii], ii);
		// Delete the temp file
		DeleteFile(saFileNames[ii]);
	}

	return 0;
}

// The following functions returns a temp file name
static BOOL get_temp_file_name(string &strFile)
{
	char sz[MAXFULLPATH];
	DWORD dw = GetTempPath(MAXFULLPATH, sz);
	if( dw )
	{
		strFile = sz;
		dw = GetTempFileName(strFile, "S_W", 0, sz);
		if( dw )
		{
			strFile = sz;
			return TRUE;
		}
	}
	return FALSE;
}
