Конвертировать spss в excel

SPSS to Excel and vice versa!

It’s simple, web-based, and requires no installation: just upload

convert

download your resulting file immediately.


Use the basic version for free, or upgrade to
coN’verter Pro
for a small fee.

From To

File size exceeds the maximum 100KB limit for free conversions. Go Pro ?
 
SAV file encoding

If available, convert variable names and labels

If available, generate a codebook out of the rawdata

Privacy note: No information about your file contents is retained on our server. The file travels to our server, is converted in-memory, and is immediately discarded: We don’t peer into your data at any time!

I want to open spss .sav data files in Excel without opening the spss files (I don’t want to convert spss data file into Excel file). I know this is possible using OLDB connection, but I don’t know how to do this.

Tomerikoo's user avatar

Tomerikoo

17.9k16 gold badges45 silver badges60 bronze badges

asked Mar 1, 2013 at 4:38

Rama Moorthy's user avatar

(Not exactly an answer for you, since do you want avoid opening the files, but maybe this helps others).

I have been using the open source GNU PSPP package to convert the sav tile to csv. You can download the Windows version at least from SourceForge [1]. Once you have the software, you can convert sav file to csv with following command line:

pspp-convert <input.sav> <output.csv>

[1] http://sourceforge.net/projects/pspp4windows/files/?source=navbar

answered Aug 26, 2015 at 8:20

Juha Palomäki's user avatar

Juha PalomäkiJuha Palomäki

26.2k2 gold badges37 silver badges42 bronze badges

3

In order to download that driver you must have a license to SPSS. For those who do not, there is an open source tool that is very much like SPSS and will allow you to import SAV files and export them to CSV.

Here’s the software

And here are the steps to export the data.

answered Jan 31, 2014 at 22:35

Ameet Wadhwani's user avatar

I help develop the Colectica for Excel addin, which opens SPSS and Stata data files in Excel. This does not require ODBC configuration; it reads the file and then inserts the data and metadata into your worksheet.

The addin is downloadable from
http://www.colectica.com/software/colecticaforexcel

answered Apr 24, 2015 at 17:10

Jeremy's user avatar

JeremyJeremy

1,9531 gold badge15 silver badges18 bronze badges

1

You can do it via ODBC. The steps to do it:

  1. Install IBM SPSS Statistics Data File Driver. Standalone Driver is enough.
  2. Create DNS via ODBC manager.
  3. Use the data importer in Excel via ODBC by selecting created DNS.

answered Mar 3, 2013 at 8:05

djhurio's user avatar

djhuriodjhurio

5,4174 gold badges27 silver badges47 bronze badges

You can use online converter, developed by me at N’counter.

This is the easiest way to open SPSS file in Excel.

1) You just have to upload your file to SPSS coN’verter at https://secure.ncounter.de/SpssConverter

2) Select some options

3) And your converted Excel file will be downloaded

No information about your file contents is retained on our server. The file travels to our server, is converted in-memory, and is immediately discarded: We don’t peer into your data at any time!

answered Dec 1, 2017 at 19:31

Lion HC's user avatar

6

I tried the below and it worked well,

Install Dimensions Data Model and OLE DB Access

and follow the below steps in excel

Data->Get External Data ->From Other sources -> From Data Connection Wizard -> Other/Advanced-> SPSS MR DM-2 OLE DB Provider-> Metadata type as SPSS File(SAV)-> SPSS data file in Metadata Location->Finish

answered Mar 14, 2013 at 4:00

Rama Moorthy's user avatar

Rama MoorthyRama Moorthy

5551 gold badge10 silver badges19 bronze badges

Содержание

  1. How to open spss data files in Excel?
  2. 7 Answers 7
  3. SPSS Converter¶
  4. Installation¶
  5. Dependencies¶
  6. Why the SPSS Converter?В¶
  7. Key SPSS Converter Features¶
  8. SPSS Converter vs Alternatives¶
  9. Questions and Issues¶
  10. Contributing¶
  11. Testing¶
  12. License¶
  13. Using the SPSS Converter¶
  14. Introduction¶
  15. Converting Data from SPSS¶
  16. Converting to Pandas DataFrame¶
  17. Converting to CSV¶
  18. Converting to JSON¶
  19. Converting to YAML¶
  20. Converting to Excel¶
  21. Converting to dict В¶
  22. Converting Data to SPSS¶
  23. Converting from Pandas DataFrame В¶
  24. Converting from CSV¶
  25. Converting from dict В¶
  26. Converting from JSON¶
  27. Converting from YAML¶
  28. Converting to Excel¶
  29. Working with Metadata¶

How to open spss data files in Excel?

I want to open spss .sav data files in Excel without opening the spss files (I don’t want to convert spss data file into Excel file). I know this is possible using OLDB connection, but I don’t know how to do this.

7 Answers 7

I converted sav to csv online: http://pspp.benpfaff.org/

(Not exactly an answer for you, since do you want avoid opening the files, but maybe this helps others).

I have been using the open source GNU PSPP package to convert the sav tile to csv. You can download the Windows version at least from SourceForge [1]. Once you have the software, you can convert sav file to csv with following command line:

In order to download that driver you must have a license to SPSS. For those who do not, there is an open source tool that is very much like SPSS and will allow you to import SAV files and export them to CSV.

I help develop the Colectica for Excel addin, which opens SPSS and Stata data files in Excel. This does not require ODBC configuration; it reads the file and then inserts the data and metadata into your worksheet.

You can do it via ODBC. The steps to do it:

  1. Install IBM SPSS Statistics Data File Driver. Standalone Driver is enough.
  2. Create DNS via ODBC manager.
  3. Use the data importer in Excel via ODBC by selecting created DNS.

You can use online converter, developed by me at N’counter.

This is the easiest way to open SPSS file in Excel.

1) You just have to upload your file to SPSS coN’verter at https://secure.ncounter.de/SpssConverter

2) Select some options

3) And your converted Excel file will be downloaded

No information about your file contents is retained on our server. The file travels to our server, is converted in-memory, and is immediately discarded: We don’t peer into your data at any time!

Источник

SPSS Converter¶

Simple utility for converting data to/from SPSS data files

The SPSS Converter is a simple utility that facilitates the easy conversion of SPSS data to / from a variety of formats, including:

Installation¶

To install the SPSS Converter, just execute:

Dependencies¶

Why the SPSS Converter?В¶

If you work with SPSS data in the Python ecosystem, you probably use a combination of two or three key libraries: Pandas, Pyreadstat, and savReaderWriter. All three libraries are vital tools, incredibly well-constructed, designed, and managed. But over the years, I have found that converting from SPSS to other file formats using these libraries requires some fairly repetitive boilerplate code. So why not make it easier?

The SPSS Converter library is a simple wrapper around the Pyreadstat and Pandas libraries that provides a clean and simple API for reading data files in a variety of formats and converting them to a variety of formats. The semantics are super simple, and should be as simple as: spss_converter.to_csv(‘my-spss-file.sav’) or spss_converter.from_json(‘my-json-file.json’) .

Key SPSS Converter Features¶

With one function call, convert an SPSS file into:

With one function call, create an SPSS data file from data in:

With one function call, generate a Pythonic data map or meta-data collection from your SPSS data file.

Decide which variables (columns) you want to include / exclude when doing your conversion.

SPSS Converter vs Alternatives¶

The SPSS Converter library is a simple wrapper around the Pyreadstat and Pandas libraries that simplifies the syntax for converting between different file formats.

While I am (I think understandably) biased in favor of the SPSS Converter, there some perfectly reasonable alternatives:

Obviously, since the SPSS Converter is just a wrapper around Pyreadstat and Pandas, you can simply call their functions directly.

Both libraries are excellent, stable, and use fairly straightforward syntax. However:

using those libraries directly does double the number of function calls you need to make to convert between different data formats, and

those libraries (and Pyreadstat in particular) provide limited validation or Pythonic object representation (less “batteries included” in its syntactical approach).

Of course, these differences are largely stylistic in nature.

When to use it?

Honestly, since initially building this wrapper I rarely use Pyreadstat and Pandas directly. Mostly, this is a matter of syntactical taste and personal preference.

However, I would definitely look to those libraries directly if I were:

writing this kind of wrapper

working in older versions of Python ( Multiple Response Sets , which are not (yet) supported by either Pyreadstat or the SPSS Converter.

Questions and Issues¶

You can ask questions and report issues on the project’s Github Issues Page

Contributing¶

We welcome contributions and pull requests! For more information, please see the Contributor Guide .

Testing¶

We use TravisCI for our build automation, Codecov.io for our test coverage, and ReadTheDocs for our documentation.

Detailed information about our test suite and how to run tests locally can be found in our Testing Reference .

License¶

The SPSS Converter is made available under an MIT License .

© Copyright 2021, Insight Industry Inc.. Revision 0368aada .

Источник

Using the SPSS Converter¶

Introduction¶

The SPSS Converter library is a simple wrapper around the Pyreadstat and Pandas libraries that provides a clean and simple API for reading data files in a variety of formats and converting them to a variety of formats. The semantics are super simple, and should be as simple as: spss_converter.to_csv(‘my-spss-file.sav’) or spss_converter.from_json(‘my-json-file.json’) .

Converting Data from SPSS¶

To read from SPSS files and convert them to a different format you can use functions whose names start with spss_converter.to_* . The examples below provide specifics:

Converting to Pandas DataFrame¶

To convert from an SPSS file to a Pandas DataFrame , simply call the to_dataframe() function:

The code above will read your data from the file my-spss-file.sav , convert it into a Pandas DataFrame , and generate an spss_converter.Metadata representation of the SPSS file’s meta-data, which includes its data map, labeling, etc.

Converting to CSV¶

To read data from an SPSS file and convert it into a CSV file, simply call the to_csv() function:

Both lines of code above will read the SPSS data from my-spss-file.sav , but the first line will store it in the str variable as_csv . The second will instead write it to the file my-csv-file.csv .

Converting to JSON¶

To read data from an SPSS file and convert it into a JSON object, simply call the to_json() function:

As Records (default)

The SPSS Converter supports two different layouts for JSON representation of data:

Records. This layout returns a JSON collection (array) of JSON objects. Each object in the collection represents one record from the SPSS file. The object is a a set of key/value pairs where each key represents a variable/column in the SPSS file and its value represents the value of that variable/column for that respondent. This is the default layout.

Table. This layout returns a JSON object that includes a schema with the data map, and a separate data key which contains a collection (array) of objects where each object represents a single record from the SPSS data file.

If no target is supplied, then the JSON representation is stored in-memory in the return value. If a target is supplied, then the JSON representation will be written to this file.

Converting to YAML¶

To read data from an SPSS file and convert it into a YAML object, simply call the to_yaml() function:

As Records (default)

The SPSS Converter supports two different layouts for YAML representation of data:

Records. This layout returns a YAML collection (array) of YAML objects. Each object in the collection represents one record from the SPSS file. The object is a a set of key/value pairs where each key represents a variable/column in the SPSS file and its value represents the value of that variable/column for that respondent. This is the default layout.

Table. This layout returns a YAML object that includes a schema with the data map, and a separate data key which contains a collection (array) of objects where each object represents a single record from the SPSS data file.

If no target is supplied, then the YAML representation is stored in-memory in the return value. If a target is supplied, then the JSON representation will be written to this file.

Converting to Excel¶

To read data from an SPSS file and convert it into a Microsoft Excel file, simply call the to_excel() function:

Both lines of code above will read the SPSS data from my-spss-file.sav , but the first line will store it in the bytes variable as_excel . The second will instead write it to the file my-excel-file.xlsx .

Converting to dict В¶

To read data from an SPSS file and convert it into a dict object, simply call the to_dict() function:

As Records (default)

The SPSS Converter supports two different layouts for dict representation of data:

Records. This layout returns a list of dict objects. Each object in the list represents one record from the SPSS file. The object is a dict whose keys each represent a variable/column in the SPSS file and whose values represent the value of that variable/column for that respondent. This is the default layout.

Table. This layout returns a dict object that includes a schema key with the data map, and a separate data key which contains a list of objects where each object represents a single record from the SPSS data file.

Converting Data to SPSS¶

To convert other sources of data to SPSS format, you can simply use any function whose names start with spss_converter.from_* . The examples below provide specifics:

Converting from Pandas DataFrame В¶

To generate an SPSS file from a Pandas DataFrame , simply call the from_dataframe() function:

The examples below all assume that the variable df contains the DataFrame whose data will be converted to SPSS format and the variable meta contains the Metadata that describes that data frame.

The code above will convert the data in the DataFrame named df , and generate it in SPSS format either in-memory or on the hard drive.

Converting from CSV¶

To read data from a CSV file and convert it into SPSS format, simply call the from_csv() function:

Both lines of code above will read the data from my-csv-file.csv , but the first line will store it in the bytesIO variable as_spss . The second will instead write it to the file my-spss-file.sav .

Converting from dict В¶

To read data from a dict and convert it into an SPSS format, simply call the from_dict() function:

Converting from JSON¶

To read data from a JSON file and convert it into SPSS format, simply call the from_json() function:

As Records (default)

The SPSS Converter supports two different layouts for JSON representation of data:

Records. This layout expects a JSON collection (array) of JSON objects. Each object in the collection represents one record in the SPSS file. The object is a a set of key/value pairs where each key represents a variable/column in the SPSS file and its value represents the value of that variable/column for that respondent. This is the default layout.

Table. This layout returns a JSON object that includes a schema with the data map, and a separate data key which contains a collection (array) of objects where each object represents a single record in the SPSS data file.

If no target is supplied, then the SPSS representation is stored in-memory in the return value. If a target is supplied, then the SPSS representation will be written to this file.

The from_json() function can accept either a filename or a string with JSON data.

Converting from YAML¶

To read data from a YAML file and convert it into SPSS format, simply call the from_yaml() function:

As Records (default)

The SPSS Converter supports two different layouts for YAML representation of data:

Records. This layout expects a YAML collection (array) of YAML objects. Each object in the collection represents one record in the SPSS file. The object is a a set of key/value pairs where each key represents a variable/column in the SPSS file and its value represents the value of that variable/column for that respondent. This is the default layout.

Table. This layout returns a YAML object that includes a schema with the data map, and a separate data key which contains a collection (array) of objects where each object represents a single record in the SPSS data file.

If no target is supplied, then the SPSS representation is stored in-memory in the return value. If a target is supplied, then the SPSS representation will be written to this file.

The from_yaml() function can accept either a filename or a string with YAML data.

Converting to Excel¶

To read data from an Excel file and convert it into SPSS format, simply call the from_excel() function:

Both lines of code above will read the data from my-excel-file.xlsx , but the first line will store it in the bytes variable as_excel . The second will instead write it to the file my-spss-file.sav .

Key to working with SPSS data is understanding the distinction between the raw data’s storage format and the metadata that describes that data. Fundamentally, think of metadata as the map of how a value stored in the raw data (such as a numerical value 1 ) can actually represent a human-readable labeled value (such as the labeled value «Female» ).

The metadata for an SPSS file can itself be quite verbose and define various rules for what can and should be expected when analyzing the records in the SPSS file. Within the SPSS Converter, this meta-data is represented using the Metadata class.

Various functions that read SPSS data produce Metadata instances, and these instances can be manipulated to restate and adjust the human-readable labels applied to your SPSS data.

Источник

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
' Исправленная версия Export_to_Excel_(BIFF).SBS
' Размещено в SPSSX-L, 15.01.2002, автор: K.Asselberghs

' Экспортирует Сводные таблицы из SPSS на один и тот же лист рабочей книги Excel.
' Таблицы разделяются пустыми строками.
' * Чтобы экспортировать и другие объекты, поправьте процедуру ExportItems().
' * ПРИМЕЧАНИЕ
'    Перед запуском скрипта, запустите Excel и выделите ячейку, с которой должна начаться вставка импортируемых таблиц.

'*****************************************************************************.

'ОПИСАНИЕ
'Этот скрипт экспортирует Сводные таблицы SPSS в Excel, используя BIFF (Binary Interchange File Format - двоичный формат файла для обмена).
'Конец ОПИСАНИЯ
'
'******************************************************
'При необходимости отредактируйте макрос Excel (см. ниже), который
'переформатирует таблицу после вставки в Excel
'******************************************************

Sub ExcelMacro()
  objExcelApp.Selection.AutoFormat Format:=&HFFFFEFC6, Number:=True, _
    Font:=True, Alignment:=True, Border:=True, Pattern:=True, Width:=True
    'Вы можете запросить в Excel выполнение этого макроса
End Sub
'
'******************************************************
'ДАЛЕЕ НИКАКИХ ИЗМЕНЕНИЙ НЕ ТРЕБУЕТСЯ
'******************************************************


'используется как заголовок в диалоговых окнах
Const SCRIPT_NAME As String = "Экспорт в рабочую книгу Excel"
'используются для подавления предупреждений и возврата прежних установок для предотвращения нежелательных диалоговых окон
Const ALERTS_PRESERVE As Boolean = False
Const ALERTS_RESTORE As Boolean = True

Option Explicit
'Вызов функции Windows API, даёт больший контроль, чем функция Wait из Sax Basic
Declare Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long)

'глобальные переменные, используются большинством процедур
Dim objExcelApp As Object
Dim objOutput As ISpssOutputDoc

'для уведомления пользователя о невозможности вставки объекта...
Dim s_intErrorCount As Integer


Sub Main
    Dim strFileName As String

    On Error Resume Next

    'Начиная с SPSS 8.0 мы можем вызывать этот скрипт из синтаксиса.
    'В таком случае, нам потребуется подавить предупреждения, которые будут приостанавливать исполнение программы.
    'Но в SPSS 7.5 это вызовет ошибку.  Посему вся обработка предупреждений встроена в процедуру Alerts.
    'Мы вызываем её здесь только для инициализации установок. Она должна быть вызвана снова для восстановления
    'установок перед окончанием работы скрипта.
    Alerts(ALERTS_PRESERVE)

    'Отменяем экспорт, если в окне результатов пусто.
    If objSpssApp.Documents.OutputDocCount > 0 Then
        Set objOutput = objSpssApp.GetDesignatedOutputDoc
    Else
        'процедура ErrorBox передаёт свои аргументы для отображения в MsgBox, но перед этим проверяет процедуру Alerts.
        ErrorBox "В SPSS отсутствуют результаты для экспорта. " & vbCrLf & _
            "Пожалуйста, выполните анализ и запустите скрипт снова.", vbExclamation, SCRIPT_NAME
        'Всегда восстанавливаем установки перед выходом!
        Alerts(ALERTS_RESTORE)
        End
    End If

    'Получим имя файла, в котором будут сохранены результаты.
    'С 8-й версии SPSS скрипт может вызываться из синтаксиса, которой передаст ему имя файла в качестве параметра.
    'Если нет, запросим имя файла у пользователя.
     '@strFileName = GetFileName()

    'Следующее условие может быть опущено,
    'тогда результаты могут быть экспортированы, но без сохранения файла.
 '@ If strFileName = "" Then
 '@     'Пользователь отменил выбор, либо указанный в синтаксисе при вызове файл не может быть перезаписан.
 '@     'Всегда восстанавливаем установки перед выходом!
 '@     Alerts(ALERTS_RESTORE)
 '@     End
 '@ End If

    'Запустим Excel и сохраним ссылку на это приложение в глобальной переменной objExcelApp.
    CreateExcel

    'Вот, наконец-то, место, где мы начинаем что-то делать по сути!
    ExportItems

    'Сохраняем файл. Следовало бы сделать это в виде подпрограммы, если бы это не ограничивалось одной строкой кода.
    '@ objExcelApp.ActiveWorkbook.SaveAs FileName:=strFileName

    'Скажем пользователю, были ли объекты, которые не удалось скопировать
    If s_intErrorCount > 0 Then
        '... но только если предупреждения не отключены
        ErrorBox "Некоторые объекты могли не вполне корректно скопироваться и вставиться в Excel." & vbCrLf & _
            "Проверьте выдачу SPSS и полученный документ Excel.", vbExclamation, SCRIPT_NAME
    End If
        MsgBox "Готово!"
    'В последний раз:
    'Всегда восстанавливаем установки перед выходом!
    Alerts(ALERTS_RESTORE)
End Sub


'Ищет объекты, подходящие для экспорта в Excel. Вставляет их в Excel и запускает форматирующий макрос.
Sub ExportItems()
    Dim objItems As ISpssItems
    Dim objItem As ISpssItem
    Dim i As Long
    Dim intFootnotes As Integer

    On Error Resume Next
    '@ objExcelApp.Workbooks.Add

    Set objItems = objOutput.Items
    For i = 0 To objItems.Count - 1
        Set objItem = objItems.GetItem(i)
        Debug.Print "Объект: " & i & ", тип: " & objItem.SPSSType & _
            ", видимый: " & objItem.Visible
        'С ОДНОЙ ИЗ СЛЕДУЮЩИХ ДВУХ СТРОК СЛЕДУЕТ СНЯТЬ КОММЕНТАРИЙ
       'If objItem.Visible And objItem.Selected Then   'копируем только выделенные объекты
        If objItem.Visible Then                         'копируем всё видимое содержимое
           'ВЫБИРАЕМ, ЧТО И КАК ДОЛЖНО БЫТЬ ЭКСПОРТИРОВАНО В EXCEL
            Select Case objItem.SPSSType
                Case SPSSPivot  ', SPSSWarning  ', SPSSNote     'пропустим Notes, если закомментировано
                    'PasteIntoExcel objItem, "Picture (Enhanced Metafile)"
                    'закомментируйте остаток этого варианта (Case), если вставляете объект как картинку
                   PasteIntoExcel objItem, "Biff"
                    'применяем макрос Excel для форматирования таблицы
                    'ExcelMacro
               'Case SPSSLog, SPSSText, SPSSTitle
                    'PasteIntoExcel objItem, "Text"
                Case SPSSChart, SPSSIGraph
                     'PasteIntoExcel objItem, "Picture (Enhanced Metafile)"
                Case Else
                    'ничего не делаем
            End Select
        End If
    Next
    Err.Clear
End Sub


'Непосредственно контролирует процесс копирования и вставки.
'Используем технику отката и повторных попыток для борьбы со скрытыми ошибками буфера обмена.
Sub PasteIntoExcel (objItem As ISpssItem, strFormat As String)
    Static intSheet As Integer

    On Error Resume Next

    Dim lngSleep As Long
    Dim nrows As Integer

    lngSleep = 100  '1/10-я секунды

    Clipboard ""    '.Clear (очистим буфер обмена)

    objOutput.ClearSelection
    objItem.Selected = True

    'Копируем объект. Следующий за этим цикл - только если возникли проблемы.
    Do
        Sleep lngSleep
        objOutput.Copy
        If Err Then
            'буфер обмена может быть недоступен в этот момент для вставки результата метода copy
            'попробуем подождать и попытатемся снова
            lngSleep = 2 * lngSleep
        End If
    Loop Until (Err = 0) Or (lngSleep > 2000)

    If Err Then 'что-то не так с копированием. Попробуем сказать об этом пользователю
        Clipboard ">>> Объект не может быть скопирован: Ошилка # " & Err & vbCrLf & Err.Description
        strFormat = "Text"
        s_intErrorCount = s_intErrorCount + 1
        Err.Clear
    End If

 '@ intSheet = intSheet + 1
 '@ If intSheet > objExcelApp.Sheets.Count Then
 '@     objExcelApp.Sheets.Add
 '@ Else
 '@     objExcelApp.Sheets("Blad" & Trim$(CStr$(intSheet))).Select
 '@ End If

    lngSleep = 100
    Do
        Sleep lngSleep

        objExcelApp.ActiveSheet.PasteSpecial Format:=strFormat, Link:=False, DisplayAsIcon:= False
                nrows = objExcelApp.Selection.Areas(1).Rows.Count + 1 'KA
        'MsgBox CStr(nrows)

        If Err Then
            Debug.Print "Paste Error: " & Err; Err.Description
            'буфер обмена в этот момент может быть недоступен для вставки
            'попробуем подождать и попытаемся снова
            lngSleep = 2 * lngSleep
        End If
    Loop Until (Err=0) Or (lngSleep > 2000)

    If Err Then
        s_intErrorCount = s_intErrorCount + 1
        Err.Clear
    End If

    objExcelApp.ActiveCell.Offset(nrows, 0).Activate  'KA

End Sub


Function GetFileName() As String
    Dim strFileName As String

    'Во-первых, проверим, не вызван ли скрипт из синтаксиса,
    'и не передано ли имя файла в качестве параметра.

    On Error Resume Next
    'следующая операция вызовет ошибку в SPSS 7.5
    strFileName = objSpssApp.ScriptParameter(0)
    If Err Then
        Err.Clear
    End If

    If strFileName <> "" Then
        'Можно стирать файл с совпадающим именем, т.к. пользователь запросил его через синтаксис
        If Dir$(strFileName) <> "" Then
            Kill strFileName
        End If
        'но иногда его нельзя стереть, если файл открыт
        If Err = 10101 Then
            Err.Clear
            'если документ открыт в Excel, попробуем закрыть его и снова попытаемся стереть
            CloseOpenDocument strFileName
            Kill strFileName
            If Err Then
                'если ничего не помогает, откажемся от экспорта
                Err.Clear
                strFileName = ""
            End If
        End If
        GetFileName = strFileName
        Exit Function
    End If

    'Если в параметрах скрипта пусто, запросим имя файла у пользователя
    Do
        'получим путь и имя файла, куда будут сохранены результаты экспорта
        '3=означает подтверждение перезаписи существующего файла
        strFileName = GetFilePath$("Output.xls","xls",,SCRIPT_NAME, 3)
        If strFileName = "" Then    'пользователь отменил операцию
            Exit Function
        End If
        'пробуем стереть файл, т.к. пользователь дал "добро"
        If Dir$(strFileName) <> "" Then
            Kill strFileName
        End If
        'но иногда его нельзя стереть, если файл открыт
        If Err = 10101 Then
            ErrorBox "Файл """ & strFileName & _
                """ в настоящий момент открыт в Excel и не может быть перезаписан. " & _
                vbCrLf & vbCrLf & _
                "Пожалуйста, укажите другой файл, " & _
                "либо закройте этот и попробуйте ещё раз.", vbExclamation, _
                SCRIPT_NAME
            Err.Clear
            strFileName = ""
        ElseIf Err Then
            'не ясно, как обрабатывать другие возможные ошибки
            Err.Clear
            Exit Function
        End If
    Loop Until strFileName <> ""

    GetFileName = strFileName
End Function


Sub CloseOpenDocument(strFileName As String)
    On Error Resume Next
    CreateExcel
    objExcelApp.Workbooks(GetName(strFileName)).Activate
    objExcelApp.ActiveWorkbook.Close
    Err.Clear
End Sub


'возвращает ссылку на приложение Excel в глобальную переменную objExcelApp.
Sub CreateExcel()
    On Error Resume Next

    'GetObject возвращает ссылку на запущенное приложение.
    Set objExcelApp = GetObject(,"Excel.Application")
 '@ If Err = 10096 Then Debug.Print "Excel не запущен, используем CreateObject"
    'CreateObject запускает Excel, если тот к настоящему моменту не был запущен.
 '@ If objExcelApp Is Nothing Then
 '@     Set objExcelApp = CreateObject("Excel.Application")
 '@ End If
    'в случае, если надо диагностировать и другие ошибки
    Debug.Print Err; Err.Description
    Err.Clear

    If objExcelApp Is Nothing Then
        ErrorBox "Перед запуском скрипта откройте рабочую книгу Excel " & vbCrLf & _
            "и выделите ячейку, с которой желаете начать вставку результатов из SPSS.", vbExclamation, SCRIPT_NAME
        'Всегда восстанавливаем установки перед выходом!
        Alerts(ALERTS_RESTORE)
        End
    End If
    objExcelApp.Visible = True

    If objExcelApp.ActiveWorkbook Is Nothing Then
        ErrorBox "Не найтено открытых рабочих книг в Excel." & vbCrLf & _
           "Перед запуском скрипта откройте рабочую книгу Excel," & vbCrLf & _
           "и выделите ячейку, с которой желаете начать вставку результатов из SPSS.", vbExclamation, SCRIPT_NAME
       'Всегда восстанавливаем установки перед выходом!
       Alerts(ALERTS_RESTORE)
       End
    End If

    'objExcelApp.Workbooks.Add
    'objExcelApp.ActivateMicrosoftApp
End Sub


'Выделяем букву диска и путь к файлу из строки.
Function GetName(strFileName As String) As String
    Dim strName As String
    Dim intPos As Integer
    Dim intPos1 As Integer

    strName = strFileName

    'Выделяем букву диска и двоеточие, если имеется.
    intPos = InStr(strName, ":")
    If intPos > 0 Then
        strName = Mid$(strName, intPos + 1)
    End If

    'Находим последний обратный слэш \.
    Do
        intPos = intPos1
        intPos1 = InStr(intPos1 + 1, strName, "\")
    Loop Until intPos1 = 0

    'убираем всё до последнего обратного слэша \.
    If intPos > 0 Then
        strName = Mid$(strName, intPos + 1)
    End If
    Debug.Print  strName

    'Убирать расширение не требуется...

    GetName = strName
End Function


'Обрабатываем свойство Alerts, которое приводит к ошибкам в SPSS 7.5.
'Вызываем с аргументом False (ложь) (ALERTS_PRESERVE) для инициализации.
'Вызываем с аргументом True (истина) (ALERTS_RESTORE) для восстановления установок
'перед завершением работы скрипта.
'Если скрипт вызван из синтаксиса, но, например, (ScriptParameter(0) <> ""),
'это подавляет выдачу предупреждений, которые будут останавливать исполнение.
Function Alerts(blnRestore As Boolean) As Boolean
    Static blnInitialized As Boolean
    Static blnAlerts As Boolean
    Static blnAlertsInitial As Boolean

    On Error Resume Next

    If Not blnInitialized Then
        blnInitialized = True

        blnAlertsInitial = objSpssApp.Alerts
        If Err Then 'spss 7.5
            blnAlertsInitial = True
            Err.Clear
        End If

        blnAlerts = (objSpssApp.ScriptParameter(0) = "")
        If Err Then 'spss 7.5
            blnAlerts = True
            Err.Clear
        End If
    End If

    If blnRestore Then
        objSpssApp.Alerts = blnAlertsInitial
        blnAlerts = blnAlertsInitial
        'blnInitialized = False
    End If

    Err.Clear
    Alerts = blnAlerts
End Function


'Обработчик вызова MsgBox: проверяет, разрешено ли выдавать сообщения
Function ErrorBox(strAlertMessage As String, intType As Integer, strTitle As String)
    On Error Resume Next
    Debug.Print strAlertMessage
    If Alerts(ALERTS_PRESERVE) Then
        ErrorBox = MsgBox(strAlertMessage, intType, strTitle)
    Else
        'Сообщения запрещены.
        ErrorBox = 0
    End If
End Function

Often complaint of students complain that it is impossible to make good graphs with SPSS.

And to be honest, I agree. There are many limitations to making graphs in SPSS. And this is why usually I always develop my graphs for research papers, theses (when I did my PhD) in Excel.

Every time when you run a statistical test in SPSS, a new window appears with of your results. This is called the OUTPUT page.

And it is possible to have all of your output results in different formats, suitable for Word, PDF and Excel. And once the data is in Excel, for example, you can make extraordinary graphs and much more!

Check the tutorial below and simply follow the steps!


TUTORIAL

Here is a step-by-step of how you can export all your results (Outputs) from SPSS to other formats:


FINAL THOUGHTS

I’m telling you, my friend: SPSS really doesn’t bite. And with a few simple clicks you can allow great insights and ideas to become projects!

And don’t forget to check all of our other tutorials, showing your how to conduct a dependent samples t-test, Independent samples t-Test, One-Way ANOVA, Cronbach Alpha and much more!

Like this post? Please share to your friends:
  • Конвертировать sig в word онлайн
  • Конвертировать shs в word онлайн
  • Конвертировать sav в excel
  • Конвертировать rtf в word онлайн с возможностью редактирования текста
  • Конвертировать ris в word