Page 1 sur 1

[Résolu] [Calc] exporter d'un tableau vers un fichier CSV

Publié : 07 déc. 2018 17:18
par carabao
Bonjour,


Je cherche le moyen pour exporter un tableau vers un fichier CSV afin d'importer des données dans agenda Google ou agenda Apple .


Le tableau en question.
Tableau à synchroniser.ods
(9.86 Kio) Téléchargé 43 fois
J'ai essayé l'enregistreur de macro mais il me semble qu'il ne tient pas compte de la sélection mais il enregistre toute la feuille. Ce que il me semble avoir lu quelque part, que c'était un fonctionnement normal.
Donc comment peut-on sélectionner uniquement le tableau et pas la feuille .


Merci


EDIT:

J'ai trouvé ce code et si je l'analyse bien, il permet d'exporter le classeur en un fichier csv
Je suppose que je peux partir de celui-ci pour enregistrer une page dans un tableau et non le classeur complet ?


Code : Tout sélectionner

Dim oDoc As Object  
Dim EnrArgs(1) As New com.sun.star.beans.PropertyValue  
Dim Chemin As String , NomFeuille As String  
 
oDoc = ThisComponent  
 
' Boucle sur les feuilles  
For i = 1 to oDoc.Sheets.Count  
   NomFeuille = oDoc.Sheets(i-1).Name  
 
   ' Active la feuille  
   ThisComponent.CurrentController.ActiveSheet = oDoc.Sheets(i-1)     
 
   Chemin = Left(oDoc.URL, Len(oDoc.URL) -  Len(Dir(ConvertFromURL(oDoc.URL)))  
 
	'--- Spécifie le filtre de conversion --- 
	EnrArgs(0).Name = "FilterName"  
	EnrArgs(0).Value = "Text - txt - csv (StarCalc)"  
 
   ' Sauvegarde dans le même répertoire que le classeur original  
   oDoc.storeToURL( ConvertToURL(Chemin & NomFeuille & ".csv"), EnrArgs()) 
 
Next

Merci

Je suppose que pour exporter le tableur, je dois modifier les lignes


en

Code : Tout sélectionner

REM  *****  BASIC  *****

Sub Synchro
Dim oDoc As Object  
Dim SSS as Object		'Sheet Source synchro
Dim RSS as Object		'Range Source synchro
Dim i As Integer  
Dim EnrArgs(1) As New com.sun.star.beans.PropertyValue  
Dim Chemin As String , NomFeuille As String  

oDoc.ThisComponent
SSS=thisComponent.Sheets.getByName("Sortie")  
RSS= SS.getCellRangeByName("C6:G200") 

 
   Chemin = Left(oDoc.URL, Len(oDoc.URL) -  Len(Dir(ConvertFromURL(oDoc.URL)))  
 
	'--- Spécifie le filtre de conversion --- 
	
	EnrArgs(0).Name = "FilterName"  
	EnrArgs(0).Value = "Text - txt - csv (StarCalc)"  
 
   ' Sauvegarde dans le même répertoire que le classeur original  
   oDoc.storeToURL( ConvertToURL(Chemin & NomFeuille & ".csv"), EnrArgs()) 
 
End Sub
 
Il me reste à mettre la commande pour exporter le tableau
pour exporter que le tableau

Re: [Calc] exporter d'un tableau vers un fichier CSV

Publié : 07 déc. 2018 21:22
par carabao
En utilisant l'enregistreur de macro, j'ai obtenu

Code : Tout sélectionner

REM  *****  BASIC  *****


sub Main
rem ----------------------------------------------------------------------
rem define variables
dim document   as object
dim dispatcher as object
rem ----------------------------------------------------------------------
rem get access to the document
document   = ThisComponent.CurrentController.Frame
dispatcher = createUnoService("com.sun.star.frame.DispatchHelper")

rem ----------------------------------------------------------------------
dim args1(0) as new com.sun.star.beans.PropertyValue
args1(0).Name = "ToPoint"
args1(0).Value = "$C$6:$G$97"

dispatcher.executeDispatch(document, ".uno:GoToCell", "", 0, args1())

rem ----------------------------------------------------------------------
dim args2(3) as new com.sun.star.beans.PropertyValue
args2(0).Name = "URL"
args2(0).Value = "file:///home/xxxxxx/synchropert500.csv.pdf"
args2(1).Name = "FilterName"
args2(1).Value = "calc_pdf_Export"
args2(2).Name = "FilterData"
args2(2).Value = Array(Array("UseLosslessCompression",0,false,com.sun.star.beans.PropertyState.DIRECT_VALUE),Array("Quality",0,90,com.sun.star.beans.PropertyState.DIRECT_VALUE),Array("ReduceImageResolution",0,true,com.sun.star.beans.PropertyState.DIRECT_VALUE),Array("MaxImageResolution",0,300,com.sun.star.beans.PropertyState.DIRECT_VALUE),Array("UseTaggedPDF",0,false,com.sun.star.beans.PropertyState.DIRECT_VALUE),Array("SelectPdfVersion",0,0,com.sun.star.beans.PropertyState.DIRECT_VALUE),Array("ExportNotes",0,false,com.sun.star.beans.PropertyState.DIRECT_VALUE),Array("ViewPDFAfterExport",0,false,com.sun.star.beans.PropertyState.DIRECT_VALUE),Array("ExportBookmarks",0,true,com.sun.star.beans.PropertyState.DIRECT_VALUE),Array("OpenBookmarkLevels",0,-1,com.sun.star.beans.PropertyState.DIRECT_VALUE),Array("UseTransitionEffects",0,true,com.sun.star.beans.PropertyState.DIRECT_VALUE),Array("IsSkipEmptyPages",0,true,com.sun.star.beans.PropertyState.DIRECT_VALUE),Array("ExportPlaceholders",0,false,com.sun.star.beans.PropertyState.DIRECT_VALUE),Array("IsAddStream",0,false,com.sun.star.beans.PropertyState.DIRECT_VALUE),Array("FormsType",0,0,com.sun.star.beans.PropertyState.DIRECT_VALUE),Array("ExportFormFields",0,false,com.sun.star.beans.PropertyState.DIRECT_VALUE),Array("AllowDuplicateFieldNames",0,false,com.sun.star.beans.PropertyState.DIRECT_VALUE),Array("HideViewerToolbar",0,false,com.sun.star.beans.PropertyState.DIRECT_VALUE),Array("HideViewerMenubar",0,false,com.sun.star.beans.PropertyState.DIRECT_VALUE),Array("HideViewerWindowControls",0,false,com.sun.star.beans.PropertyState.DIRECT_VALUE),Array("ResizeWindowToInitialPage",0,false,com.sun.star.beans.PropertyState.DIRECT_VALUE),Array("CenterWindow",0,false,com.sun.star.beans.PropertyState.DIRECT_VALUE),Array("OpenInFullScreenMode",0,false,com.sun.star.beans.PropertyState.DIRECT_VALUE),Array("DisplayPDFDocumentTitle",0,true,com.sun.star.beans.PropertyState.DIRECT_VALUE),Array("InitialView",0,0,com.sun.star.beans.PropertyState.DIRECT_VALUE),Array("Magnification",0,0,com.sun.star.beans.PropertyState.DIRECT_VALUE),Array("Zoom",0,100,com.sun.star.beans.PropertyState.DIRECT_VALUE),Array("PageLayout",0,0,com.sun.star.beans.PropertyState.DIRECT_VALUE),Array("FirstPageOnLeft",0,false,com.sun.star.beans.PropertyState.DIRECT_VALUE),Array("InitialPage",0,1,com.sun.star.beans.PropertyState.DIRECT_VALUE),Array("Printing",0,2,com.sun.star.beans.PropertyState.DIRECT_VALUE),Array("Changes",0,4,com.sun.star.beans.PropertyState.DIRECT_VALUE),Array("EnableCopyingOfContent",0,true,com.sun.star.beans.PropertyState.DIRECT_VALUE),Array("EnableTextAccessForAccessibilityTools",0,true,com.sun.star.beans.PropertyState.DIRECT_VALUE),Array("ExportLinksRelativeFsys",0,true,com.sun.star.beans.PropertyState.DIRECT_VALUE),Array("PDFViewSelection",0,0,com.sun.star.beans.PropertyState.DIRECT_VALUE),Array("ConvertOOoTargetToPDFTarget",0,false,com.sun.star.beans.PropertyState.DIRECT_VALUE),Array("ExportBookmarksToPDFDestination",0,false,com.sun.star.beans.PropertyState.DIRECT_VALUE),Array("SignPDF",0,false,com.sun.star.beans.PropertyState.DIRECT_VALUE),Array("_OkButtonString",0,"",com.sun.star.beans.PropertyState.DIRECT_VALUE),Array("Watermark",0,"",com.sun.star.beans.PropertyState.DIRECT_VALUE),Array("EncryptFile",0,false,com.sun.star.beans.PropertyState.DIRECT_VALUE),Array("PreparedPasswords",0,,com.sun.star.beans.PropertyState.DIRECT_VALUE),Array("RestrictPermissions",0,false,com.sun.star.beans.PropertyState.DIRECT_VALUE),Array("PreparedPermissionPassword",0,Array(),com.sun.star.beans.PropertyState.DIRECT_VALUE),Array("Selection",0,,com.sun.star.beans.PropertyState.DIRECT_VALUE),Array("SignatureLocation",0,"",com.sun.star.beans.PropertyState.DIRECT_VALUE),Array("SignatureReason",0,"",com.sun.star.beans.PropertyState.DIRECT_VALUE),Array("SignatureContactInfo",0,"",com.sun.star.beans.PropertyState.DIRECT_VALUE),Array("SignaturePassword",0,"",com.sun.star.beans.PropertyState.DIRECT_VALUE),Array("SignatureCertificate",0,,com.sun.star.beans.PropertyState.DIRECT_VALUE),Array("SignatureTSA",0,"",com.sun.star.beans.PropertyState.DIRECT_VALUE),Array("UseReferenceXObject",0,false,com.sun.star.beans.PropertyState.DIRECT_VALUE))
args2(3).Name = "SelectionOnly"
args2(3).Value = false

dispatcher.executeDispatch(document, ".uno:ExportTo", "", 0, args2())

rem ----------------------------------------------------------------------
dim args3(9) as new com.sun.star.beans.PropertyValue
args3(0).Name = "Properties.UseUserData"
args3(0).Value = true
args3(1).Name = "Properties.DeleteUserData"
args3(1).Value = false
args3(2).Name = "Properties.Title"
args3(2).Value = ""
args3(3).Name = "Properties.Subject"
args3(3).Value = ""
args3(4).Name = "Properties.KeyWords"
args3(4).Value = ""
args3(5).Name = "Properties.Description"
args3(5).Value = ""
args3(6).Name = "Properties.AutoReload"
args3(6).Value = false
args3(7).Name = "Properties.AutoReloadTime"
args3(7).Value = 0
args3(8).Name = "Properties.AutoReloadURL"
args3(8).Value = ""
args3(9).Name = "Properties.AutoReloadFrame"
args3(9).Value = ""

dispatcher.executeDispatch(document, ".uno:SetDocumentProperties", "", 0, args3())


end sub


C'est OK pour le PDF mais pas pour le CSV. Un peu long comme code, non ?

Re: [Calc] exporter d'un tableau vers un fichier CSV

Publié : 08 déc. 2018 08:33
par Jurassic Pork
hello,
voici un exemple de code pour exporter les données de la feuille 1 en fichier csv :

Code : Tout sélectionner

Sub SaveSheetToCsv()
Document = ThisComponent  'assigns the current document to the variable document
Sheets = Document.Sheets  'get the container of all Sheets
Sheet = Sheets(0)   'get the first sheet
Document.CurrentController.setActiveSheet(Sheet)
Dim Propval(1) as New com.sun.star.beans.PropertyValue
Propval(0).Name = "FilterName"
Propval(0).Value = "Text - txt - csv (StarCalc)"
Propval(1).Name = "FilterOptions"
Propval(1).Value ="59,34,0,1,1"   'ASCII  59 = ;  34 = "
FileName = "M:\test\ExportCsv.txt"
FileURL = convertToURL(FileName)
Document.StoreToURL(FileURL, Propval())
End Sub
Pour les options d'exportation voir ici

Ami calmant, J.P

Re: [Calc] exporter d'un tableau vers un fichier CSV

Publié : 08 déc. 2018 09:37
par carabao
merci pour ton aide

Si je comprend bien ta macro


Elle ne permet pas de cibler uniquement un tableau sur la page mais la page en entière
Et d'après le chemin pour la sauvegarde, celle-ci ne tournerait que sous windows ? Pas mac, linux ?

Je te pose la question, car les utilisateurs qui utiliseront mon classeur, ont soit Win, Mac ou linux

Suis-je dans le bon ?


Merci

Re: [Calc] exporter d'un tableau vers un fichier CSV

Publié : 08 déc. 2018 12:41
par Churay
Bonjour
carabao a écrit :Et d'après le chemin pour la sauvegarde, celle-ci ne tournerait que sous windows ? Pas mac, linux ?
Format Windows

Code : Tout sélectionner

FileName = "M:\test\ExportCsv.txt"
qui est mis au Format URL et qui fonctionne avec les divers OS

Code : Tout sélectionner

FileURL = convertToURL(FileName)

Re: [Calc] exporter d'un tableau vers un fichier CSV

Publié : 08 déc. 2018 15:38
par carabao
Ok, merci beaucoup. Je me disais aussi que "convertToURL" voulait dire quelque chose concernant les chemins. Je suis débutant mais je me soigne.

Sur le même sujet:
Comment puis-je sélectionner une plage et non la feuille pour l'exportation CSV ou PDF. De plus il y a qu'un tableau dans une feuille à exporter. Hors ici, il me semble qu'il y a une boucle pour plusieurs feuilles

Je pensais mettre quelque chose comme cela:

FS = thisComponent.Sheets.getByName("Sortie")
PS = SS.getCellRangeByName("C7:G131")

ici:

Code : Tout sélectionner

Document = ThisComponent  'assigns the current document to the variable document
Sheets = Document.Sheets  'get the container of all Sheets
Sheet = Sheets(0)   'get the first sheet
Document.CurrentController.setActiveSheet(Sheet)
Mais je ne parvient pas le mettre en œuvre.


FS = Feuille Source
PS = Plage source


De plus a-t-il moyen d'avoir une plage d'exportation dynamique en fonction par exemple d'une valeur TEST d'une cellule par exemple si C45 = "" alors plage de la table à exporter C7:G44 ?


Merci

Re: [Calc] exporter d'un tableau vers un fichier CSV

Publié : 08 déc. 2018 16:50
par Dude
carabao a écrit :exporter un tableau vers un fichier CSV afin d'importer des données dans agenda Google ou agenda Apple
Plus simple, fabriquer un ICS.
Voir le projet ad hoc : https://forum.openoffice.org/fr/forum/v ... 26&t=18054

Re: [Calc] exporter d'un tableau vers un fichier CSV

Publié : 08 déc. 2018 16:55
par Jurassic Pork
Avec l'extension EasyDev (voir ici) il y a une fonction d'export de plage dans un fichier csv.
Exemple pour exporter la plage sélectionnée :

Code : Tout sélectionner

Dim options(0) As New com.sun.star.beans.NamedValue

util = createUnoService("org.universolibre.EasyDev")

range = ThisComponent.CurrentSelection

path = "/home/USER/test.csv"
data = range.getDataArray()
options(0).Name = "delimiter"
options(0).Value = ";"
util.exportCSV(path, data, options)
Ami calmant, J.P

Re: [Calc] exporter d'un tableau vers un fichier CSV

Publié : 08 déc. 2018 17:09
par Churay
FS = thisComponent.Sheets.getByName("Sortie")
PS = SS.getCellRangeByName("C7:G131")
SS est au mieux un objet NULL

Une légère correction :
FS = thisComponent.Sheets.getByName("Sortie")
PS = FS.getCellRangeByName("C7:G131")
Ainsi, ça devrait mieux le faire

De la doc :
AOO : https://www.openoffice.org/api/docs/com ... dex-3.html
LO : https://api.libreoffice.org/docs/idl/ref/classes.html
Sans oublier a Bible

Re: [Calc] exporter d'un tableau vers un fichier CSV

Publié : 08 déc. 2018 17:55
par carabao
Merci à tous pour tous vos liens.

Je suis un peu noyé entre easyDEV, ICS ....... mais je vais essayer de faire uj tri dans toutes ces documentations.

Merci

Re: [Calc] exporter d'un tableau vers un fichier CSV

Publié : 08 déc. 2018 19:03
par Churay
Pour la programmation LibreOffice ou AOO, une bonne base de départ reste la Bible

Re: [Calc] exporter d'un tableau vers un fichier CSV

Publié : 08 déc. 2018 20:02
par carabao
Merci

Re: [Calc] exporter d'un tableau vers un fichier CSV

Publié : 09 déc. 2018 10:05
par carabao
je suis enfin parvenu à mettre au point le code ci-après, en lisant les différents retours de ce fil et les nombreux exemples de ce forum

Code : Tout sélectionner

Option Explicit

Sub Main
Dim LibOClasseur AS object
Dim LibOFeuille As Object
Dim maxligne As Long

Dim oSheet AS Object, oCursor AS Object, sURL As String
Dim nRow AS Long, nCol AS Long, aPieces(), sCsv As String
dIM oUCB AS Object, oFlux AS Object, oTexte AS Object
	sURL = ThisComponent.URL : aPieces = Split(sURL, "/")
	aPieces(UBound(aPieces)) = "Mon Fichier.csv" : sURL = Join(aPieces,"/")

	oTexte = createUnoService("com.sun.star.io.TextOutputStream")
	oUCB = createUnoService("com.sun.star.ucb.SimpleFileAccess")
	IF oUCB.Exists(sURL) Then oUCB.Kill(sURL) 
	oFlux = oUCB.openFileWrite(sURL)
	oTexte.OutputStream = oFlux : oTexte.Encoding = "iso-8859-15"
	
	oSheet = thisComponent.CurrentController.ActiveSheet
	oCursor = oSheet.createCursor : oCursor.gotoEndOfUsedArea(True)
	
 
   LibOClasseur = thiscomponent 
	LibOFeuille = LibOClasseur.sheets.getByName("Sortie")

	maxligne=LibOFeuille.getCellByPosition(15,1).string
[raye]
'	FOR nRow = 0 TO oCursor.RangeAddress.EndRow[/raye]

		FOR nRow = 6 TO maxligne

	
	[raye]'	FOR nCol = 0 TO oCursor.RangeAddress.EndColumn[/raye]
		FOR nCol = 1 TO 6
	
			IF oSheet.getCellByPosition(nCol, nRow).String <> "" Then
				sCsv = sCsv & oSheet.getCellByPosition(nCol, nRow).String & ","
		END IF
		NEXT nCol
		sCsv = sCsv & CHR(10)
		' Au-delà de 4096 octets, on sauvergarde la chaîne pour revenir à 0
		IF LEN(sCsv) > 2^12 Then
			oTexte.writeString(LEFT(sCsv,LEN(sCsv)-2))
			sCsv = ""
		 END IF
	NEXT nRow
	oTexte.writeString(LEFT(sCsv,LEN(sCsv)-2))
	
	oFlux.closeOutput : oTexte.closeOutput
End Sub

J'ai ajouté ce code pour avoir la possibilité automatiquement de modifier la plage à exporter

Code : Tout sélectionner

  LibOClasseur = thiscomponent 
	LibOFeuille = LibOClasseur.sheets.getByName("Sortie")

	maxligne=LibOFeuille.getCellByPosition(15,1).string
La cellule (15,1 donc P1) dans la feuille contient un nombre. il est est calculé en faisant la différence entre deux dates donc un nombre de service donc un service = une ligne

Code : Tout sélectionner

	FOR nCol = 1 TO 6
j'ai mis 6 pour commencer à la sixième ligne (Au dessus, c'est des informations non pertinentes pour la synchro)



Merci à tous pour vos liens, vos exemples,vos pistes.


EDIT1: j'ai juste une virgule en trop dans la dernière colonne (sur chaque ligne). Comment peut-on faire pour retirer cette virgule ?
EDIT2: cette virgule n’empêche pas l'exportation.


merci