csv-io.c 2.01 KB
Newer Older
1 2 3
/*
 * csv-io.c: save/read Sheets using a CSV encoding.
 *
4
 * Miguel de Icaza <miguel@gnu.org>
5 6 7 8 9 10
 *
 */

#include <config.h>
#include <stdio.h>
#include <gnome.h>
11 12
#include "plugin.h"
#include "gnumeric.h"
13
#include "file.h"
14
#include "libcsv.h"
15

16
static struct csv_table load_and_probe_table;
17

18
static void
19
load_table_into_sheet (struct csv_table *table, Sheet *sheet)
20
{
21
	int row;
22

23 24 25
	for (row = 0; row < table->height; row++){
		Cell *cell;
		int col;
26

27
		printf ("Row: %d has %d cols\n", row, CSV_WIDTH (table, row));
28 29 30
		for (col = 0; col < CSV_WIDTH (table, row); col++){
			cell = sheet_cell_new (sheet, col, row);
			cell_set_text_simple (cell, CSV_ITEM (table, row, col));
31
		}
32
			
33 34 35
	}
}

36
static Workbook *
37 38
csv_read_workbook (const char* filename)
{
39 40 41
	Workbook *book;
	Sheet *sheet;
	char *name;
42

43
	book = workbook_new ();
44 45
	if (!book)
		return NULL;
46

47 48 49 50
	name = g_strdup_printf (_("Imported %s"), g_basename (filename));
	sheet = sheet_new (book, name);
	g_free (name);
	
51 52
	workbook_attach_sheet (book, sheet);

53 54 55 56 57 58 59 60
	load_table_into_sheet (&load_and_probe_table, sheet);
	
	/*
	 * Destroy and tag as invalid
	 */
	csv_destroy_table (&load_and_probe_table);
	load_and_probe_table.row = NULL;
	
61 62 63 64 65 66 67
	return book;
}


static gboolean
csv_probe (const char *filename)
{
68 69 70 71 72 73 74 75
	FILE *f;

	f = fopen (filename, "r");
	if (f == NULL)
		return FALSE;
	
	if (csv_load_table (f, &load_and_probe_table) == -1){
		load_and_probe_table.row = NULL;
76 77
		return FALSE;
	}
78 79 80 81 82 83 84 85
	fclose (f);
	
	/*
	 * Careful:
	 *
	 * We assume that the load routine is going to be invoked inmediately
	 */
	return TRUE;
86 87
}

88 89
static int
csv_can_unload (PluginData *pd)
90
{
91 92
	/* We can always unload */
	return TRUE;
93 94
}

95
static void
96 97
csv_cleanup_plugin (PluginData *pd)
{
98
	file_format_unregister_open (csv_probe, csv_read_workbook);
99 100 101
}

int
102
init_plugin (PluginData * pd)
103
{
104
/*	file_format_register_open (1, _("Comma Separated Value (CSV) import"), csv_probe, csv_read_workbook); */
105 106
	pd->can_unload = csv_can_unload;
	pd->cleanup_plugin = csv_cleanup_plugin;
107 108
	pd->title = g_strdup (_("Comma Separated Value (CSV) module"));
	
109 110
	return 0;
}