Как конвертировать mysql в excel

One of the main aspects of modern business is gathering and sharing information with others.

In this article, several ways to export/import MySQL data to an Excel file will be explained. The first method will show the exporting process when the SELECT INTO … OUTFILE statement is used. After that, the Excel features for export/import MySQL data, as well as MySQL add-in for Excel, will be explained, and in the end, the Export to Excel option from the ApexSQL Database Power Tools for VS Code extension will be shown.

The following methods will be used:

  • The SELECT INTO … OUTFILE statement
  • The From Database feature in Excel
  • The MySQL for Excel add-in
  • Export to Excel using a third-party software

Export/Import MySQL data to Excel using the SELECT INTO … OUTFILE statement

One of the commonly used MySQL statement which can be included in the SELECT statements for exporting data to specific (e.g., .txt, .CSV) file format is SELECT INTO … OUTFILE statement. This statement writes a selected row to a file. Columns and line terminators can be specified to produce a specific output format.

In a query editor, execute a SELECT statement which results want to be exported, add the location where data should be exported, and specify the file format. In the example below, the .txt file format is used:

SELECT `actor`.`actor_id`
   ,`actor`.`first_name`
   ,`actor`.`last_name`
   ,`actor`.`last_update`
 FROM `sakila`.`actor`
 INTO OUTFILE 'C:/ProgramData/MySQL/MySQL Server 8.0/Uploads/actor.txt' FIELDS TERMINATED BY ',' ENCLOSED BY '"' LINES TERMINATED BY 'rn'
 

Export MySQL data to txt file

When the above statement is executed, all exported data will be in the actor.txt file:

Exported MySQL data in .txt file

Under the specified location:

Location of exported MySQL data

  • For more details about SELECT INTO … OUTFILE statement, see How to export MySQL data to CSV article.

When the data is exported, let’s open it in Excel and save it in .xlsx file format.

Open Excel and under the Data tab, click the From Text/CSV button:

export/import MySQL data using Excel feature

Navigate to the location of the exported .txt file and click Import:

Import data to Excel

In the newly opened dialog, choose appropriate delimiter and click Transform Data:

Set delimiter

In the Power Query Editor window, it is necessary to set some additional settings (e.g., add the name of the columns):

Set the column name

When all is set, click the Close & Load command:

Load data to Excel sheet

The data will be loaded in a separate sheet:

Imported MySQL data to Excel

Save newly imported data in .xlsx file format:

Save newly imported data in .xlsx file format

Export/Import MySQL data to Excel using the From Database feature

Similar to the method in the section above, Excel provides one more option to load data from the MySQL database to Excel.

In the Data tab, under the Get Data list, choose the From MySQL Database command:

export/import MySQL data to Excel using From MySQL Database feature

In the MySQL database dialog, enter server and database name from which you want to load data and click the OK button:

MySQL database dialog

On the next window, under the Database tab, enter credentials for the user that have permission to access the targeted database and click the Connect button:

MySQL connection credentials

From the Navigator window, choose the tables, views, etc. from which to load data:

Navigator dialog

Click the Transform Data button. The Power Query Editor window will appear with desired data in it. Now, the steps for loading data are the same as we explained in the previous section:

Power Query Editor window

Use MySQL for Excel add-in

MySQL for Excel is the Windows-based add-in that integrates into Excel under the Data tab that provides export/import MySQL data capabilities.

To install MySQL for Excel add-in first download the MySQL for Excel MSI file. Before starting with installation, please check that the following requirements are fulfilled:

  • .NET Framework 4.5.2 (Client or Full Profile)
  • Microsoft Office Excel 2007 or later (for Microsoft Windows)
  • Visual Studio 2010 Tools for Office Runtime. MySQL Installer may install this for you. This requirement is different than Office Developer Tools for Visual Studio, which is not a substitute
  • An available MySQL server connection

(source: MySQL for Excel Guide / Installation)

Otherwise, some errors may occur during the installation process, like that one from the image below, when the Visual Studio 2010 Tools for Office Runtime is not installed:

Note: The Microsoft Visual Studio Tools for Office Runtime must be installed prior to running this installation.

The Microsoft Visual Studio Tools for Office Runtime must be installed prior to running this installation warning message

Installation

The installation process is straightforward. Go to the location where the installer (mysql-for-excel-1.3.8.msi) is downloaded, right-click on it, and from the context menu, choose the Install command:

mysql-for-excel-1.3.8.msi installer

When the installation wizard is launched, click Next:

mysql-for-excel-1.3.8.msi installation wizard

On the Destination Folder step, choose a location where the MySQL For Excel 1.3.8 will be installed and click Next:

mysql-for-excel-1.3.8 install location

On the next step, click the Install button to start the installation of MySQL For Excel 1.3.8:

Ready to install MySQL For Excel 1.3.8 dialog

On the last step, click the Finish button to close the setup wizard:

Last MySQL For Excel installation dialog

Now when Excel is launched, the MySQL for Excel add-in will appear in the top-right corner of the Data tab:

MySQL for Excel add-in in the Data tab

Connect to MySQL database

To start MySQL for Excel, click on the MySQL for Excel icon under the Data tab. In the panel that shows find and click the New Connection button:

Connect to MySQL database in order to export/import MySQL data

In the MySQL Server Connection window, enter the name for the connection in the Connection Name box (e.g., Sakila_database).

From the Connection Method drop-down list, chose the method to connect to RDBMS (e.g., Standard (TCP/IP)).

In the Hostname box, enter a name or IP address of the server host (e.g., localhost). Under the Port box, enter the TCP/IP port number (e.g., 3306). For the Username and Password fields, enter the credentials for the user that have access to the specified server in the Hostname field:

MySQL Server Connection dialog

Optional, from the Default Schema drop-down list, the default schema can be selected.

To confirm that connection to the MySQL Server works properly, click the Test Connection button:

Test MySQL connection

Click the OK button on the MySQL Server Connection window for MySQL for Excel to create a connection in MySQL for Excel panel:

Choose the MySQL connection from which want to export/import MySQL data

Double-click on the newly created connection will list all available databases from that MySQL server:

Choose the MySQL database from which want to export/import MySQL data

Double-click on a database, in the MySQL for Excel panel, will list all tables, views, and procedures from that database:

Choose the MySQL table from which want to export/import MySQL data

To import data, on the MySQL for Excel panel, select the desired table, and click the Import MySQL Data button. The Import Data window will appear:

Import settings

When all settings are set, click the Import button. The imported data will look something like this:

Exported MySQL data

This add-in can return all rows, or a specified range of rows, from a specified table. It cannot import data stored in two different tables, perform table joins, or filter data.

More details about MySQL for Excel tool can be found on the MySQL for Excel page.

Export to Excel using a third-party software

Using the Export to Excel feature from ApexSQL Database Power Tools for VS Code, query results can be exported to MySQL data from the results grid in just a few steps. Besides exporting data to Excel, this VS Code extension provides a couple of more exporting options, such as export data to JSON, CSV, and HTML file format.

In a query editor of the VS Code extension, execute a query from which you want to be data exported. In the top right corner of the Results grid, click the Export to Excel button:

export/import MySQL data using Export to Excel feature

In the Save as window, enter a name and location for a new Excel file and click the Save button:

Save exported MySQL data

The exported data will look like this:

Exported MySQL data by using Export to Excel feature

August 12, 2020

Если нужно быстро и единоразово выгрузить данные из таблицы MySQL в Exel файл, то помогут следующие способы:

1

Экспорт через PHPMyAdmin

В PHPMyAdmin при экспорте можно выбрать формат «CSV for MS Excel»:

Экспорт через PHPMyAdmin

При открытии полученного файла в Excel будет сбита кодировка:

Excel будет сбита кодировка

Чтобы это исправить, нужно открыть csv файл в редакторе типа Notepad++ и изменить кодировку на ANSI:

Notepad++ изменить кодировку на ANSI:

Результат:

2

Экспорт через HTML таблицу

Смысл метода состоит в том чтобы PHP-скриптом сформировать HTML таблицу:

<?php
$dbh = new PDO('mysql:dbname=db_name;host=localhost', 'логин', 'пароль');
$sth = $dbh->prepare("SELECT * FROM `test`");
$sth->execute();
$items = $sth->fetchAll(PDO::FETCH_ASSOC);
?>
		
<table>
	<tr>
		<td>ID</td>
		<td>Категория</td>
		<td>Название</td>
		<td>Описание</td>
	</tr>
	<?php foreach($items as $row): ?>
	<tr>
		<td><?php echo $row['id']; ?></td>
		<td><?php echo $row['category']; ?></td>
		<td><?php echo $row['name']; ?></td>
		<td><?php echo $row['text']; ?></td>
	</tr>
	<?php endforeach; ?>
</table>

PHP

Результат работы скрипта:

Полученную таблицу копируем и вставляем в чистый лист Microsoft Exel:

3

Экспорт через PHPExcel

Третий метод – сформировать xls-файл в библиотеке PHPExcel (PHPExcel.zip).

//spl_autoload_unregister('autoload');
require_once __DIR__ . '/PHPExcel/Classes/PHPExcel.php';
require_once __DIR__ . '/PHPExcel/Classes/PHPExcel/Writer/Excel2007.php';

$xls = new PHPExcel();
$xls->setActiveSheetIndex(0);
$sheet = $xls->getActiveSheet();

// Шапка
$sheet->getStyle("A1:D1")->getFont()->setBold(true);
$sheet->setCellValue("A1", 'ID');
$sheet->setCellValue("B1", 'Категория');
$sheet->setCellValue("C1", 'Название');
$sheet->setCellValue("D1", 'Описание');

// Выборка из БД
$dbh = new PDO('mysql:dbname=db_name;host=localhost', 'логин', 'пароль');
$sth = $dbh->prepare("SELECT * FROM `test`");
$items = $sth->fetch(PDO::FETCH_ASSOC);

$index = 2;
foreach ($items as $row) {
	$sheet->setCellValue("A" . $index, $row['id']);
	$sheet->setCellValue("B" . $index, $row['category']);
	$sheet->setCellValue("C" . $index, $row['name']);
	$sheet->setCellValue("D" . $index, $row['name']);
	$index++;
}

// Отдача файла в браузер
header("Expires: Mon, 1 Apr 1974 05:00:00 GMT");
header("Last-Modified: " . gmdate("D,d M YH:i:s") . " GMT");
header("Cache-Control: no-cache, must-revalidate");
header("Pragma: no-cache");
header("Content-type: application/vnd.ms-excel" );
header("Content-Disposition: attachment; filename=prods.xlsx");
 
$objWriter = new PHPExcel_Writer_Excel2007($xls);
$objWriter->save('php://output'); 

exit(); 

PHP

Результат:

The typical way to achieve this is to export to CSV and then load the CSV into Excel.

TL;DR:

  • For a server-side Excel-friendly CSV file from a SELECT query, run this:

    SELECT ... FROM someTable WHERE etc
    INTO OUTFILE 'someTableExport.csv' CHARACTER SET utf8mb4
    FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"' ESCAPED BY ''
    LINES TERMINATED BY 'rn';
    
  • For a server-side Excel-friendly CSV file use mysqldump like so:

    mysqldump -h serverHostName -u mysqlUserName -p --tab="someTableExport.csv" --fields-optionally-enclosed-by=0x22 --fields-escaped-by='' --fields-terminated-by=0x2C --lines-terminated-by=0x0D0A --databases databaseName --tables table1 table2 table3
    
  • For a client-side Excel-friendly CSV file using mysqlsh (MySQL Shell) like so:

    mysqlsh --user="mysqlUserName" --host="serverHostName" --port=3306 --schema="databaseName"
    # Once connected, run this:
    util.exportTable("tableName", "file:///C:/Users/You/Desktop/test.csv", { dialect: "csv", fieldsEscapedBy: ""})
    

First, a caution about Excel:

Excel’s vs. MySQL’s default CSV formats:

Remember that Excel has its own underdocumented ideas about how CSV files should be formatted and these stand in-contrast to MySQL’s own ideas about CSV files; though Excel is largely compliant with RFC 4180 you still need to prod and poke MySQL and its associated tooling to generate CSV files that Excel won’t misinterpret:

Excel MySQL (default) MySQL (when configured)
SQL NULL Zero-length value Literal N Literal NULL
Text values that don’t contain commas, quotes, or line-breaks Not enclosed Not enclosed Enclosed in "
Text values that contain commas, quotes, or line-breaks Enclosed in " Not enclosed Enclosed in "
Non-text values Not enclosed Not enclosed Not enclosed
Line-breaks and tabs in text values Literal Escaped as [r]n Literal
Double-quotes in text values Doubled-up "" Escaped as " Doubled-up ""
Field separator , t (Tab) ,
Record separator rn n rn
Commas inside non-quoted text values (Results in broken table data) Not escaped Will always be quoted if the value contains a comma
UTF-8 support
  • Excel 2007-2013: — Requires leading UTF-8 BOM
  • Excel 2016+: — Handles BOM-less UTF-8 with some prodding
Use utf8mb4.
Do not specify the older broken utf8 or utf8mb3 encodings.
Use utf8mb4

As per the table above, MySQL can generate Excel-friendly CSV files, excepting that SQL NULLs will always be interpreted by Excel as literal text, though it’s trivial to use PowerQuery or even just Find-and-Replace in Excel to replace them with empty cells.

Excel and special CSV text markers

  • If any of your text values start with = then you’ll need to manually fudge those as even when quoted Excel will interpret the text following = as a formula instead of literal text.
  • Also watch out for leading text like sep= too.

Excel and UTF-8 encoding:

Surprisingly, it wasn’t until Excel was 31 years old (Excel 2016) when Excel added built-in support for UTF-8 encoding in files without needing a BOM, but it still defaults to importing and exporting CSV files using your system-default non-Unicode encoding (e.g. Windows-1252).

  • When importing CSV into Excel, be sure to select Codepage 65001 for correct UTF-8 handling as Excel still defaults to non-Unicode-based codepages for some reason.
    • Note that opening a CSV file in Excel won’t display the Text Import Wizard. (As of Excel 2021) you need to copy-and-paste CSV text into Excel and use the popup menu to use the legacy (frozen-in-1994) wizard, or use Data > From Text/CSV on the ribbon to use the newer (but less flexible, imo) PowerQuery-based CSV import wizard:

Your options:

Option SELECT INTO OUTFILE mysqldump --tab mysqldump > file.csv mysqlsh MySQL Workbench
Server-side CSV True True True True Broken
Remote (client-side) CSV False False False True Broken
MySQL Server version support All versions All versions All versions Only 5.7 and later All versions

Option 1: Exporting an Excel-friendly CSV using INTO OUTFILE:

  • You can do a server-side CSV export by using the INTO OUTFILE clause of a SELECT query.
    • Because this is «normal» SQL that’s executed by the MySQL server this works regardless of whatever MySQL client tool you’re using, so you don’t need to install MySQL Workbench.
    • …but because this is a server-side export you need to have permission to write to the server’s filesystem which you might not have, in which case consider using specialty export tools like mysqldump (see below).
  • MySQL’s OUTFILE clause has a number of optional subclauses that must be specified for some-level of compatibility with Excel’s own CSV reader:
    • FIELDS...
      • TERMINATED BY (default: 't', for Excel use ',')
      • [OPTIONALLY] ENCLOSED BY (default: '', should be '"' with the OPTIONALLY keyword)
      • ESCAPED BY (default: '\', for Excel use '')
    • LINES...
      • TERMINATED BY (default: 'n', for Excel use 'rn')
      • STARTING BY (default: '', for Excel you can omit this or use the MySQL default).
    • Do not use ENCLOSED BY (without the preceding OPTIONALLY keyword) as that will enquote all values, regardless of type (i.e. it will enquote int values which will cause Excel (by default) to interpret them as text (strings) instead of numbers).
  • Note that there is no option to instruct MySQL to output SQL NULLs as empty-fields, and so Excel will interpet them as unquoted strings of text (i.e. as "NULL"), so you’ll want to do a Find-and-Replace in Excel after importing the file.
  • If your INTO OUTFILE <fileName> filename (e.g. 'someTableExport.csv' above) is not an absolute path then it will be saved into your database’s datadir directory. Run SHOW VARIABLES LIKE 'datadir'; to get the path. Note that you might not necessarily have read/write permission for new files under that directory.

So your query (SELECT * FROM document WHERE documentid...) would look something like this:

SELECT
    *
FROM
    document 
WHERE
    documentid IN ( SELECT documentid FROM TaskResult WHERE taskResult = 2429 )
INTO
    OUTFILE 'someTableExport.csv'
    FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"', ESCAPED BY ''
    LINES TERMINATED BY 'rn';

Option 2: Exporting an Excel-friendly CSV using mysqldump:

  • To store dump into CSV file using the --tab command-line option, as per mysqldump‘s documentation.
  • Unfortunately mysqldump‘s --tab= option won’t work for remote MySQL servers: this is because --tab="fileName.csv" can only represent a path on the server.
    • While you can use stdout redirection to generate a local file (i.e. mysqldump --etc > output.csv) you cannot use the --fields-terminated-by and other format options with stdout, making it useless for Excel-compatible output. So if you’re remote and cannot ssh-in then you will need to use MySQL Shell (mysqlsh) instead (see below).
  • Note that mysqldump does not support SELECT queries for dumping data: it does support simple WHERE-style filters with the --where=<expr> option but this doesn’t support things like filtering using an INNER JOIN (though as a workaround you could SELECT into a new table, then run mysqldump on that new table. Note that you cannot use TEMPORARY TABLE with mysqldump as Temporary Tables are connection-scoped).

In the OP’s case, due to limitations inherent in how the --where= command-line option works, they’ll want to export both tables (document and TaskResult) and apply their filter logic in Excel PowerQuery or similar. Perform the export like so:

mysqldump -h serverHostName -u mysqlUserName -p --tab="someTableExport.csv" --fields-optionally-enclosed-by=0x22 --fields-escaped-by='' --fields-terminated-by=0x2C --lines-terminated-by=0x0D0A --databases databaseName --tables document TaskResult
  • The above command-line should work without modification in Windows’ cmd.exe, macOS’s zsh, and bash on Linux — provided mysqldump is in your PATH.

  • The use of hex-encoded chars means sidestepping the hassle of figurig out how to pass double-quotes and line-breaks as literals in your shell and terminal (0x22 is ", 0x2C is ,, and 0x0D0A is rn).

  • Avoid using the --password=<value> (aka -p<value>) option on
    the mysqldump command-line, as it will mean your password will be saved in plaintext to your terminal or console history file, which is an obvious massive security risk.

    • So if you’re in an interactive command-line session need to specify a password then mysqldump will prompt you for the password immediately when the program runs so it won’t be saved to your history file.
    • If you want to run mysqldump in a non-interactive context (e.g. from within a web-application, daemon, or other process) then there’s (normally) no history file to worry about, but you should still consider alternative approaches before resorting to handling passwords in an insecure way.
  • If you don’t specify an absolute path but use a short (unqualified) filename like INTO OUTFILE 'output.csv' or INTO OUTFILE './output.csv' theb it will store the output file to the directory specified by SHOW VARIABLES LIKE 'datadir';.

Option 3: Exporting an Excel-friendly CSV using MySQL Workbench:

Unfortunately, you can’t (unless you don’t have any double-quotes anywhere in your data): As of late 2022 MySQL Workbench has an open bug regarding its own CSV export feature: output files never escape double-quote characters in text, so pretty much all CSV-handling software out there will report a malformed CSV file or import data to the wrong columns — so this makes it completely unsuitable for use with Excel.

Option 4: Exporting an Excel-friendly CSV using MySQL Shell (aka mysqlsh):

  • This is probably the simplest option, but you might need to install the MySQL Shell as it doesn’t come in-box in most MySQL installations.
  • MySQL Shell supports connecting to MySQL Server 5.7 and later (but not older versions). If you’re still using MySQL Server 5.6 or earlier (then you really should update to 5.7 or later anyway) you’ll have to stick with mysqldump run locally on the MySQL Server itself (but you can use an ssh session, of course).
    • The new «MySQL X» protocol (mysqlx://user@host/schema) is not supported by MySQL 5.7, but mysqlsh supports non-X connections with old-style command-line parameters.
  1. Install MySQL Shell if it isn’t already installed.
  2. If you start MySQL Shell without any command-line arguments (e.g. because you use the Start Menu shortcut on Windows)) then use the connect command to connect.
    • For MySQL 5.7 use connect mysql://username@hostname

    • For MySQL 8.0+ there are a variety of ways to connect, including the «MySQL X» protocol as well as «Classic» connections. Consult the docs for more info.

    • If your username contains literal @ characters then you need to percent-encode them (e.g. if you’re using Azure MySQL then your full username will be like username%40servername@servername.mysql.database.azure.com).

    • Immediately after you submit the connect command you will be prompted for your password interactively.

  3. If you can start mysqlsh with arguments, then you can run mysqlsh --user="userName" --host="hostName" --port=3306 --schema="dbName" directly without using the connect command.
  4. Once connected, run the util.exportTable(tableName, outputUri, options) command with the following arguments:
    • tableName: your table name.
      • Unfortunately there doesn’t seem to be a way to apply a WHERE filter or export the results of a SELECT query, (though as with mysqldump you could always save your query results to a new TABLE, then export that table, then DROP TABLE when you’re done with it. Remember that TEMPORARY TABLE won’t work here as tables created in one session aren’t visible from any other session — and mysqlsh will have its own session.
    • outputUri: To save the file locally use a file:/// URI.
      • On Windows you can use a forward-slash as a directory-name separator instead of a backslash. e.g. file:///C:/Users/Me/Desktop/export.csv.
    • options: To ensure compatibility with Excel specify { dialect: "csv", fieldsEscapedBy: ""}.
      • The dialect: "csv" option sets Excel-compatible defaults for all-but-one of the OUTFILE parameters, so you must also specify fieldsEscapedBy: "", otherwise SQL NULL will be be rendered as N (literally) while double-quotes and line-breaks inside text values will be backslash-escaped, which Excel doesn’t support.

Input file

Our API uses a .SQL file as input.
This could be a MySQL dump from the mysqldump tool
or an output of any other tool that returns SQL.
The file should contain CREATE TABLE and INSERT/UPDATE statements.

Max file size for web uploads: 50 GB
Register to upload big files via Amazon S3.

Output file

The API will return a ZIP archive of .XLSX files, one for each input file.
Since Excel has a limit of about one million rows,
it could be that the rows are divided into several files.

Conversion methods

Using our Java tool

Download the

RebaseData client Java tool
.
To convert your database using RebaseData, run the following command:

                    java -jar client-0.0.5.jar convert --output-format=xlsx file.sql output-dir/
                

Using CURL

Replace file.sql with the path to the MySQL .SQL file you want to convert.

The file output.zip will contain a Excel file, one for each input file. If something went wrong, output.zip contains the error message.

curl -F files[]=@file.sql 'https://www.rebasedata.com/api/v1/convert?outputFormat=xlsx&errorResponse=zip' -o output.zip

How long does it take?

The conversion process takes between 15 seconds and multiple minutes. It depends on the size of the database.

You can also use your favourite tool

  • Read MySQL .SQL using PHP
  • Read MySQL .SQL using Python
  • Read MySQL .SQL using Ubuntu

Why use RebaseData?

  • Strong security.
  • Convert online without installing MySQL Server.
  • Works with Windows, Mac and Linux.
  • Use an API to convert your databases.
  • Professional support.

Terms

  • We don’t guarantee for the success or correctness of the conversion
  • You are only allowed to convert your own database files
  • By using RebaseData, you agree to our general terms
«MySQL Последнее обновление 04 апреля 2019 06:16:12 (UTC / GMT +8 часов)

script1adsense2code

script1adsense3code

Установка и настройка

Импорт и экспорт данных между MySQL и Excel стал намного проще в Excel 2007, чем в предыдущих версиях. Чтобы изучить эту функцию, вам нужно установить MySQL для Excel.

Вы можете установить компонент MySQL для Excel при установке MySQL Community Server 6. Или вы можете установить его как дополнение к существующей установке MySQL Server. Однако для установки этого компонента есть некоторые предпосылки.

MySQL для Excel Требования

Для установки MySQL для Excel Installer на вашем компьютере должно быть установлено следующее:

  • .NET Framework 4.0 (клиент или полный профиль).

  • Microsoft Office Excel 2007 или выше, для Microsoft Windows.

  • Visual Studio Tools для Office 4.0 и MySQL Installer могут установить это для вас.

  • Доступное соединение с MySQL Server.

MySQL для Excel загружается и выполняется путем выбора вкладки меню «Данные» в Excel, а затем выбора значка «База данных MySQL для Excel». Это открывает новую боковую панель Excel с доступными опциями MySQL для Excel. Панель навигации со значком MySQL для Excel показана на следующем снимке экрана:

«MySQL

Редактировать данные MySQL в Excel

MySQL для Excel позволяет загружать и редактировать данные MySQL непосредственно из Microsoft Excel, или же вы можете сделать это вручную, нажав «Принять изменения».

В приведенном ниже примере используется таблица расположения примера базы данных сотрудников, но экран будет выглядеть одинаково для любой таблицы. В MySQL для Excel откройте соединение MySQL, щелкните схему сотрудника, затем выберите таблицу местоположений, нажмите «Изменить данные MySQL», затем выберите «Импорт», чтобы импортировать данные в новый лист Microsoft Excel для редактирования.

Вот пошаговое руководство по редактированию и фиксации данных:

Шаг 1:

Загрузить Microsoft Office Excel 7

«MySQL

Шаг 2:

Нажмите на вкладку данных , см. Рисунок выше, значок базы данных «MySQL для Excel» появится ниже.

«MySQL

Шаг 3:

Нажмите на значок базы данных «MySQL для Excel». Он открывает новую боковую панель Excel с доступными параметрами MySQL для Excel. Панель навигации со значком MySQL для Excel показана на следующем рисунке.

«MySQL

Здесь наша База данных является сотрудником, и мы работаем с таблицей местоположений , но экран будет выглядеть одинаково для любой таблицы.

Шаг 4:

В боковой панели MySQL для Excel откройте соединение MySQL двойным щелчком мыши. Здесь наше соединение — Локальный экземпляр MySQL5.6, и для принятия пароля появится следующий экран.

«MySQL

Шаг 5:

Введите пароль для соединения с сервером MySQL. Базы данных будут отображаться в боковой панели MySQL для Excel. Наша База данных является сотрудником. Смотрите следующую картинку.

«MySQL

Шаг 6:

Дважды щелкните по нужной базе данных, и отобразятся таблицы в базе данных. Наш стол — это местоположение. Смотрите следующую картинку.

«MySQL

Шаг 7:

Выберите таблицу, которую вы хотите редактировать, нажмите «Редактировать данные MySQL» на панели навигации, как показано выше, и посмотрите следующий снимок экрана.

«MySQL

Шаг 8:

Нажмите кнопку «Импорт», как указано на картинке выше, и посмотрите следующий снимок экрана. Появятся данные выбранной таблицы, и если вы наведете курсор на диапазон данных, в противном случае появится кнопка «Восстановить данные и зафиксировать изменения» (указанная красным прямоугольником).

«MySQL

Шаг 9:

Здесь, в нашей таблице, идентификатор первого столбца является первичным ключом. Если мы изменим значение ID в ячейке A19 вместо 17 и нажмем клавишу ввода, цвет этой ячейки будет зеленым. Теперь мы изменили значение ячейки F16 Лондона и нажмите клавишу ввода, цвет ячейки изменится на зеленый, а желтый цвет в последнюю очередь означает, что ячейки принимают новые данные. Введенные здесь данные вставляются в таблицу MySQL.

«MySQL

Шаг 10:

Теперь, если мы нажмем кнопку «Восстановить данные», посмотрите следующий снимок экрана.

«MySQL

Здесь на картинке выше, если вы нажмете кнопку «Обновить данные из БД», данные будут обновлены и отобразятся исходные данные из БД, а если вы нажмете «Восстановить измененные данные», вы потеряете только что сделанные изменения. На этом этапе, если вы нажмете кнопку «Применить изменения», посмотрите следующий снимок экрана.

«MySQL

Здесь на рисунке выше вы видите сообщение об ошибке, и цвет ячейки A19 изменился с зеленого на красный, потому что столбец идентификатора является первичным ключом, а уникальность здесь нарушена. Теперь мы вернули значение ячейки A19 в исходное значение, то есть 18, и нажмите кнопку Commit Changes, и теперь посмотрим на снимок экрана ниже.

«MySQL

На изображении выше показано, как цвета ячейки F16 преобразованы из зеленого в синий, что означает успешное выполнение изменений. Теперь вы можете закрыть сохранение окна Excel или нет, но таблица базы данных была обновлена. Вы можете видеть это, чтобы сделать шаг снова. Если вы установили флажок «Автоматическая фиксация», эффект сразу же отобразится на вашем листе, и данные будут обновлены в базе данных MySQL.

Импорт данных MySQL в Excel

Данные можно импортировать из MySQL в электронную таблицу Microsoft Excel с помощью параметра «Импорт данных MySQL» после выбора таблицы, представления или процедуры для импорта.

Прежде всего, вы делаете первые 6 шагов, описанных выше в «Редактировании данных MySQL в Excel», затем выбираете таблицу, которую хотите импортировать. Здесь наш стол — местоположение. Поэтому выберите таблицу местоположений, а затем нажмите «Импорт данных MySQL» и посмотрите на скриншот, показанный ниже.

«MySQL

Выбор столбцов для импорта

По умолчанию все столбцы выбраны и будут импортированы. Определенные столбцы могут быть выделены (или не выбраны) с использованием стандартного метода Microsoft Windows: либо Control + щелчок мышью для выбора отдельных столбцов, либо Shift + щелчок мышью для выбора диапазона столбцов.

Белый цвет фона указывает, что столбец или столбцы были выбраны, и они готовы к импорту, с другой стороны, серый цвет указывает, что столбцы не выбраны и столбец не будет импортирован.

Если щелкнуть правой кнопкой мыши в любом месте сетки предварительного просмотра, откроется контекстное меню с параметром «Нет» или «Выбрать все» в зависимости от текущего состояния.

Таблица импорта

Включить имена столбцов в качестве заголовков: по умолчанию этот параметр включен, и он обрабатывает имена столбцов в верхней части электронной таблицы Microsoft Excel как строку «заголовков» и будет вставлен в качестве заголовка.

Ограничить и строки и начать с строки : по умолчанию этот параметр отключен, если включен, это ограничивает диапазон импортируемых данных. Параметр Limit to по умолчанию равен 1, и этот предел может быть изменен путем определения количества строк для импорта. Параметр «Начать со строки» по умолчанию равен 1, т. Е. Начинается с первой строки, и его можно изменить, определяя номер, с которого начинается импорт. Каждый параметр имеет максимальное значение COUNT (строки) в таблице.

Теперь предполагается, что мы хотим импортировать столбцы LOATION_ID и CITY. Щелкните мышью по столбцу LOCATION_ID, затем нажмите и удерживайте клавишу CTRL, щелкните столбец CITY и посмотрите следующий снимок экрана.

«MySQL

Теперь, если мы нажмем кнопку «Импорт», все строки для этих двух столбцов будут импортированы в Microsoft Excel Worksheet.

Предполагается, что мы хотим импортировать только 6 строк, начиная с 3-го ряда. Теперь посмотрите следующий снимок экрана.

«MySQL

Здесь на рисунке выше показано, что все столбцы выбраны, и значение Limit to равно 6, что означает, что будет импортировано 6 строк, и начало импорта начнется с 3-й строки, потому что мы установили значение Start with Строка 3. Теперь нажмите кнопку «Импорт» и посмотрите следующий снимок экрана.

«MySQL

Добавить данные Excel в MySQL

Данные электронной таблицы Microsoft Excel можно добавлять в таблицу базы данных MySQL с помощью параметра «Добавить данные Excel в таблицу».

Отображения столбцов

Сопоставление столбцов Excel со столбцами MySQL можно выполнить автоматически (по умолчанию), вручную или с помощью хранимой процедуры сопоставления. Чтобы добавить данные из Excel в MySQL, необходимо выполнить следующий шаг:

Сначала выполните 6 шагов «Редактирования данных MySQL в Excel», затем введите записи в таблицу Excel, совместимую со структурой таблицы MySQL, в которую вы хотите добавить записи. Вот пример, в котором мы взяли только одну строку, вы можете взять более одной строки и затем выбрать записи. Смотрите следующий снимок экрана.

«MySQL

Теперь нажмите «Добавить данные Excel в таблицу», как упомянуто выше, и посмотрите на экран как.

«MySQL

Здесь на картинке выше, вы ищете два цвета для легенды. Один красный, а другой зеленый.

Зеленый цвет указывает, что исходный столбец сопоставлен (сопоставленный означает, что исходные столбцы в приведенной выше сетке, созданной в электронной таблице, были сопоставлены со структурой таблицы MySQL в качестве целевых столбцов, показанных в нижней сетке) с целевым столбцом и здесь на рисунке выше. показывает, что все исходные столбцы были сопоставлены с целевыми столбцами.

Если вы перетащите заголовок любого целевого столбца на зеленый цвет и оставите его вне сетки, цвет целевого столбца будет красным, а цвет исходного столбца — серым. Смотрите на картинке ниже.

«MySQL

Здесь на рисунке выше целевой столбец 4 стал красным, а исходный столбец 4 — серым.

Красный цвет означает, что целевой столбец не сопоставлен, а серый цвет означает, что исходный столбец не сопоставлен.

Следует отметить, что исходный столбец может быть сопоставлен с несколькими целевыми столбцами, хотя это действие генерирует диалоговое окно с предупреждением, и при щелчке правой кнопкой мыши по целевому столбцу отображается меню с параметрами либо «Удалить сопоставление столбцов» для одного столбца, либо «Очистить». Все сопоставления для всех столбцов.

Предположим, мы отображаем вручную путем перетаскивания исходного столбца 4 с целевыми столбцами 4 и столбцами 5 Целевой столбец 4 будет отображаться просто, но при выполнении процесса для целевого столбца 5 появится диалоговое окно с предупреждением, показанное ниже.

«MySQL

Методы картирования

Вот посмотрите три метода отображения:

Метод автоматического сопоставления пытается сопоставить имена исходных столбцов Excel с именами столбцов целевой таблицы MySQL.

В методе сопоставления вручную имена столбцов источника перетаскиваются вручную с именами столбцов назначения. После выбора Автоматического метода также можно выполнить метод ручного перетаскивания.

Вы можете сохранить свои собственные стили сопоставления с помощью кнопки « Сохранить сопоставление» и сохранить имя, например «name (dbname.tablename)», и оно будет доступно в поле со списком «Метод сопоставления».

Сохраненные сопоставления могут быть удалены или переименованы в диалоговом окне « Дополнительные параметры ».

Расширенные настройки

Если мы нажмем кнопку «Дополнительные параметры», диалоговое окно будет выглядеть примерно так:

«MySQL

Выполните автоматическое сопоставление при открытии диалогового окна : с помощью этих параметров автоматически сопоставляется цель и источник при открытии диалогового окна «Добавить данные».

Автоматически сохранять сопоставление столбцов для данной таблицы . Чтобы проверить этот параметр, сохраняется каждая подпрограмма сопоставления после выполнения операции добавления. Процедура отображения сохраняется в формате «tablenameMapping (dbname.tablename)». Это может быть выполнено вручную с помощью кнопки Store Mapping.

Перезагрузите сохраненное сопоставление столбцов для выбранной таблицы автоматически : если существует сохраненная подпрограмма сопоставления, которая сопоставляет все имена столбцов в исходной сетке с целевой сеткой, то она автоматически загружается.

Расширенные параметры поля данных:

Используйте первые 100 (по умолчанию) строк данных Excel для предварительного просмотра и расчета типов данных. Это определяет количество строк, которые отображает предварительный просмотр, и значения, которые влияют на функцию автоматического сопоставления.

При проверке Использовать отформатированные значения данные из Excel обрабатываются как Текст, Двойной или Дата. Это включено по умолчанию. Если мы отключим его, существующие данные никогда не будут обрабатываться как тип даты, поэтому, например, это означает, что дата может быть представлена в виде числа.

Сохраненные сопоставления столбцов — это список сохраненных сопоставлений столбцов, которые были сохранены с помощью функции «Автоматически сохранять сопоставление столбцов для данной таблицы» или вручную с параметром «Сопоставление хранилищ».

После завершения всех шагов, если мы нажмем кнопку «Добавить», появится следующий экран.

«MySQL

Экспорт данных Excel в MySQL

Данные электронной таблицы Microsoft Excel можно экспортировать в новую таблицу базы данных MySQL с помощью параметра « Экспорт данных Excel в новую таблицу» . Сначала вы делаете первые 6 шагов, описанных выше, в разделе « Редактирование данных MySQL в Excel» . Затем введите несколько записей с нужным заголовком в электронную таблицу Excel и выберите записи. Теперь посмотрите пример записи на следующем рисунке —

«MySQL

Теперь нажмите «Экспорт данных Excel в новую таблицу» с помощью стрелки на изображении выше и посмотрите на следующий экран.

«MySQL

1 — Укажите уникальное имя для таблицы MySQL. Предположим, что имя таблицы MySQL «счет-фактура»

2 — Если установлен переключатель радиокнопки Добавить первичный ключ, будет добавлен дополнительный столбец первичного ключа, вы можете изменить имя столбца, и по умолчанию тип данных будет целым числом, которое отображается в 7.

3 — Когда вы установите переключатель «Использовать существующие столбцы», имена столбцов будут доступны в поле со списком, и вы сможете выбрать столбец первичного ключа из списка, и столбец будет выбран. Предположим, вы выбрали столбец INVOICE_NO, посмотрите следующую картинку.

«MySQL

Здесь на рисунке выше был выбран столбец INVOICE_NO, и теперь вы можете изменить имя столбца (точка 6), тип данных (точка 7) и ограничение (точка 9), которые активны.

4 — Если вы установите флажок Первая строка содержит имена столбцов (пункт 4), первый столбец в ваших данных Excel будет заголовком, в противном случае это будет столбец1, столбец2 и т. Д.

5 — Предположим, вы изменили тип данных и имя столбца для других столбцов, которые вы можете нажать на заголовок столбца. Предполагая, что мы хотим изменить тип данных INVOICE_DT, нажмите на INVOICE_DT, и этот столбец будет выбран, а затем вы можете использовать пункты 6,7 и 9.

6 — Вы можете изменить имя столбца.

7 — Вы можете изменить тип данных

8 — Расширенный параметр показывает следующее диалоговое окно.

«MySQL

Расширенные настройки

Используйте первые 100 (по умолчанию) строк данных Excel для предварительного просмотра и вычисления типов данных : этот параметр определяет количество строк, отображаемых при предварительном просмотре, и указанные значения влияют на функцию автоматического сопоставления.

Анализировать и пытаться определить правильный тип данных на основе содержимого поля столбца. Этот параметр пытается анализировать данные и определять тип данных для столбца. Когда столбец содержит несколько типов данных, он определяется как VARCHAR.

Добавить дополнительный буфер к длине VARCHAR (округлить до 12, 25, 45, 125, 255) : если он включен, он автоматически определяет тип данных и устанавливает значение VARCHAR, а затем находит максимальную длину для всех строк в столбце, и округляет максимальную длину до одной из указанных выше длин и, если она отключена, то длина VARCHAR устанавливается равной длине самой длинной записи в электронной таблице Excel.

Автоматически установите флажок «Индекс» для столбцов с целочисленными значениями : по умолчанию этот параметр включен, и тогда для столбцов с целочисленным типом данных будет включен параметр «Создать индекс» по умолчанию.

Автоматически установите флажок «Разрешить пустой» для столбцов без индекса: по умолчанию этот параметр включен, а при включении для столбцов без флажка «Создать индекс» автоматически включается параметр конфигурации «Разрешить пустой».

Использовать отформатированные значения: по умолчанию этот параметр включен, и данные из Excel обрабатываются как текстовые, двойные или даты, но если они отключены, они независимы, то есть не имеют определенного типа данных.

Удалить столбцы, которые не содержат данных, в противном случае пометьте их как «Исключенные»: если этот параметр включен, столбцы без данных в Excel удаляются и не отображаются на панели предварительного просмотра. По умолчанию этот параметр отключен, и тогда эти столбцы будут существовать, но с включенным параметром «Исключить столбец».

После завершения всех настроек нажмите кнопку «Экспортировать» и увидите следующий снимок экрана:

«MySQL

Предыдущий: MySQL DROP
Далее: Резервное копирование и восстановление MySQL

Понравилась статья? Поделить с друзьями:
  • Как конвертировать jpg в word чтобы можно было редактировать
  • Как конвертировать jpg в word с распознаванием текста
  • Как конвертировать jpg в word онлайн с возможностью редактирования текста
  • Как конвертировать jpg в word doc
  • Как конвертировать img в word