2016-05-24 5 views
0

拡張子.sqlのファイルがいくつかあり、すべて同じ方法でフォーマットされています。私はExcel(CSV、テーブルなど)で使用可能な形式に変換したいと考えています。私は非常に大きなハードルを持っていますが、私はプログラマーではなく、ITの制限があるので、MySQLサーバーをセットアップすることはできません。同様に、ここでは回避策としてアプリケーションをインストールすることはできません。それと.sqlのテーブルファイルをExcelに変換する

の方法のうち、すべての私のSQLコードが同じ形式でされています

-- 
-- Table structure for table `cruises` 
-- 

DROP TABLE IF EXISTS `cruises`; 
CREATE TABLE `cruises` (
    `id` int(11) unsigned NOT NULL AUTO_INCREMENT, 
    `project` varchar(32) DEFAULT NULL, 
    `itinerary_id` varchar(255) DEFAULT NULL, 
    `title` varchar(255) DEFAULT NULL, 
    `ship_name` varchar(64) DEFAULT NULL, 
    `duration` int(11) DEFAULT NULL, 
    `departure_port` varchar(64) DEFAULT NULL, 
    `departure_time` timestamp NULL DEFAULT NULL, 
    `inside` int(11) DEFAULT '0', 
    `oceanview` int(11) DEFAULT '0', 
    `balcony` int(11) DEFAULT '0', 
    `suite` int(11) DEFAULT '0', 
    `studio` int(11) NOT NULL DEFAULT '0', 
    `spa` int(11) NOT NULL DEFAULT '0', 
    `haven` int(11) NOT NULL DEFAULT '0', 
    `is_lowest_price` tinyint(1) DEFAULT '0', 
    `create_time` timestamp NULL DEFAULT CURRENT_TIMESTAMP, 
    PRIMARY KEY (`id`), 
    UNIQUE KEY `unique` (`project`,`itinerary_id`,`title`,`ship_name`,`duration`,`departure_port`,`departure_time`) 
) ENGINE=InnoDB AUTO_INCREMENT=28076 DEFAULT CHARSET=utf8; 

-- 
-- Dumping data for table `cruises` 


LOCK TABLES `cruises` WRITE; 
INSERT INTO `cruises` VALUES (22625,'disneycruise','10_europe_copenhagen_dover','10-Night Northern Europe Cruise from Copenhagen to Dover','Disney Magic',10,'Copenhagen','2017-06-18 00:00:00',6805,7585,10585,30585,0,0,0,0,'2016-05-14 10:15:19'),(22634,'disneycruise','10_mediteranean_barcelona','10-Night Mediterranean Cruise from Barcelona','Disney Magic',10,'Barcelona','2017-07-28 00:00:00',6556,7856,10456,31456,0,0,0,0,'2016-05-14 10:15:19') 

私はオンラインコンバータ(CodeBeautify)と別のものを使用してみましたが、彼らはありませんので、私は12,000以上のラインを持っています仕事に行く。さらに、データを分割することは、必要な書式設定(各ピースにテーブルステートメントを挿入する)と時間的制約のため、実際にはオプションではありません。

SQLファイル全体をExcelに貼り付けるマクロを作成しました。それは問題を抱えています。なぜなら、SQLをExcelにコピー&ペーストすると、それはテキストと列の設定を使用するため非常に脆弱になるため、それらに非常に注意する必要があるからです。さらに、12,000行のSQL insert table文が1行にあるため、データのセクション全体を削除できます。私のマクロのほとんどは、テーブル形式になるようにコピーされるものを操作することです。それは間違いなく小さなデータサンプルでも機能しますが、今述べた理由でうまく拡張できません。また、私はこの特定のデータダンプにいくつかの非常に概略的な接続をしていますが、これは一般的なcreate tableファイルでは機能しません。

Sub SQLtoExcelConverter() 
'Paste your SQL from Apple's Cruise Center into A1 of the Input sheet. 

Dim OutputData As Worksheet 
Dim SQLData As Worksheet 
Set OutputData = ThisWorkbook.Sheets("Output") 
Set SQLData = ThisWorkbook.Sheets("Input") 

'Find out the rows in which the headers for the SQL data are residing 
titleRowStart = SQLData.Columns.Find("CREATE TABLE").Row + 1 
titleRowEnd = SQLData.Columns.Find("PRIMARY KEY").Row - 1 

'Places headers on the Output Page 
For i = titleRowStart To titleRowEnd 
    OutputData.Cells(1, i + 1 - titleRowStart).Formula = "=MID(Input!A" & i & ", FIND(""`"",Input!A" & i & ")+1, FIND(""`"", Input!A" & i & ", FIND(""`"", Input!A" & i & ")+1)-FIND(""`"",Input!A" & i & ")-1)" 
    OutputData.Cells(1, i + 1 - titleRowStart).Value = OutputData.Cells(1, i + 1 - titleRowStart).Value 
Next i 

'Finds the Rows where thetable data is sorted. Extremely sketch code here 
dataRowstart = SQLData.Columns.Find("INSERT INTO", SearchOrder:=xlByColumns).Row 
dataRowEnd = SQLData.Columns.Find("/*!40000 ALTER TABLE `cruises` ENABLE KEYS */;").Row - 1 

'Cleans the data 
SQLData.Range("A" & dataRowstart & ":A" & dataRowEnd).Select 
'Removes the initial table setting 
Selection.Replace What:="INSERT INTO `cruises` VALUES (", Replacement:="", _ 
    LookAt:=xlPart, SearchOrder:=xlByColumns, MatchCase:=False, SearchFormat _ 
    :=False, ReplaceFormat:=False 
'Replaces the delimiter between rows by a strange character char(19) since excel needs a 1 character delimiter 
ch1 = Chr(19) 
Selection.Replace What:="),(", Replacement:=ch1, LookAt:=xlPart, _ 
    SearchOrder:=xlByColumns, MatchCase:=False, SearchFormat:=False, _ 
    ReplaceFormat:=False 
'Starts the separation process 
Selection.TextToColumns Destination:=Range("A" & dataRowstart), DataType:=xlDelimited, _ 
    TextQualifier:=xlDoubleQuote, ConsecutiveDelimiter:=False, Tab:=False, _ 
    Semicolon:=False, Comma:=False, Space:=False, Other:=True, OtherChar _ 
    :=ch1, TrailingMinusNumbers:=True 
'Heals data that was chopped in the inital copy into the spreadsheet 
For i = dataRowstart + 1 To dataRowEnd 
    SQLData.Cells(i, 1).Value = Chr(39) & SQLData.Cells(i, 1) 
    SQLData.Cells(i - 1, FindNextEmpty(SQLData.Cells(i - 1, 1)).Column - 1).Value = SQLData.Cells(i - 1, FindNextEmpty(SQLData.Cells(i - 1, 1)).Column - 1).Value & SQLData.Cells(i, 1).Value 
    SQLData.Cells(i, 1).Delete Shift:=xlShiftToLeft 
Next i 

'Copies all the data over to the Output page 
SQLData.Rows(dataRowstart & ":" & dataRowEnd).Select 
i = 2 
For Each c In Selection 
    If Not IsEmpty(c) Then 
     OutputData.Cells(i, 1).Value = c.Value 
     i = i + 1 
    End If 
Next c 

'Splits all the data again by commas 
OutputData.Range("A2:A" & ColumnLength("A", OutputData)).TextToColumns Destination:=Range("A2"), DataType:=xlDelimited, _ 
    TextQualifier:=xlSingleQuote, ConsecutiveDelimiter:=False, Tab:=False, _ 
    Semicolon:=False, Comma:=True, Space:=False, Other:=False, OtherChar:= _ 
    ch2, TrailingMinusNumbers:=True 

'Resets TextToColumns settings so that the next copy-paste isn't messed up 
SQLData.Range("I1").Value = 1 
SQLData.Range("I1").TextToColumns Destination:=Range("I1"), DataType:=xlDelimited, _ 
     TextQualifier:=xlDoubleQuote, ConsecutiveDelimiter:=False, Tab:=False, _ 
     Semicolon:=False, Comma:=False, Space:=False, Other:=False, OtherChar _ 
     :="~", FieldInfo:=Array(1, 1), TrailingMinusNumbers:=True 
y = FindNextEmpty(OutputData.Cells(1, 1)).Column - 1 
OutputData.Cells(OutputData.Cells(Rows.Count, y).End(xlUp).Row, y).Replace What:=");", Replacement:="", _ 
    LookAt:=xlPart, SearchOrder:=xlByColumns, MatchCase:=False, SearchFormat _ 
    :=False, ReplaceFormat:=False 

MsgBox "If your data came out all wrong it's possible the text to columns settings were tampered with. Try recopying your data and running the macro again." 
End Sub 

Public Function FindNextEmpty(ByVal rCell As Range) As Range 
'Finds the first empty cell downwards in a column. 



With rCell 
    'If the start cell is empty it is the first empty cell. 
    If Len(.Formula) = 0 Then 
     Set FindNextEmpty = rCell 
     'If the cell just below is empty 
    ElseIf Len(.Offset(0, 1).Formula) = 0 Then 
     Set FindNextEmpty = .Offset(0, 1) 
    Else 
     'Finds the last cell with content. 
     '.End(xlDown) is like pressing CTRL + arrow down. 
     Set FindNextEmpty = .End(xlToRight).Offset(0, 1) 
    End If 
End With 
End Function 
Public Function ColumnLength(Column As String, ByVal WS As Worksheet) As Long 

ColumnLength = WS.Cells(Rows.Count, Column).End(xlUp).Row 


End Function 
+0

@cg - 最良の方法は、データベースにインポートすることで、それをエクスポートするか、ストレージエンジンをCSVに変更します。あまりにもないと秘密のデータではない場合は、それらを圧縮し、私を送信することができます。私はあなたのためにすぐに変更されます –

+1

[mysqldump-to-csv](https://github.com/jamesmishra/mysqldump-to-csv)のようなものを見てください – Tom

+0

@BerndBuffen残念ながら私は毎週設定しています1時間の修正が本当に役立つわけではありません。ありがとう、結構です。 –

答えて

0

あなたは、これは私が非常に迅速に一緒にノックしてきたものです。この

Sub ImportMySQLDumptoExcel() 
    Dim intF As Integer 
    Dim i As Long 
    Dim vSql() As String, strSql As String, temp As String 
    Dim vSqls As Variant, tempArr As Variant 

    intF = FreeFile() 
    ' Set this to your .sql file path 
    Open "SQLDUMPFILEPATH" For Input As #intF 
    strSql = Input(LOF(intF), #intF) 
    Close intF 
    vSql = Split(strSql, ";") 

    ' Row Counter 
    i = 1 

    For Each vSqls In vSql 
     If InStr(1, vSqls, "Values (", vbTextCompare) > 0 Then 
      temp = Trim(Right(vSqls, Len(vSqls) - (InStr(1, vSqls, "Values (", vbTextCompare) + 7))) 
      temp = Trim(Left(temp, Len(temp) - 1)) 
      temp = Replace(temp, "'", "") 
      tempArr = Split(temp, ",") 

      ' Change this to where you want your results to go 
      With Sheet1 
       Range(.Cells(i, 1), .Cells(i, UBound(tempArr))) = tempArr 
       i = i + 1 
      End With 
     End If 
    Next 
End Sub 

ような何かを試みることができます。それはあなたのSQLファイルを開き、VALUES (を含む各行を読んで、行をきれいにしようとします。

これはSQLファイルに特有のものであり、場合によっては変更する必要があります。

world.sqlここでは例:MySQL World Databaseを使って説明しました。あなたは、異なるデータ型のために、いくつかの処理(例えば、整数)を追加する必要がありますので、これは文字列としてExcelのシートのすべてのセルを移入します

+0

これは、Excelのコピー・ペーストの問題に役立ちます。私は現在、私のデータを正しく貼り付けていない理由を見るためにデバッグしていますが、確かに確実なスタートです。私は結果を望む部分を書き直して、これを働かせました。私もtempArrの分割を ")に変更しました(そして、私が望んでいた各行をもう一度(コンマで区切って)処理しました。この理由で私も引用符を置き換えませんでした。 –

+0

私はそれがあなたのSQLファイルのいくつかの改造を必要としたかもしれないと言ったが、それは助けてうれしい – Tom

+0

私はあなたの最近の投稿の1つを経由していたと私の場合を試してみました。私はパス "c:\ Excelvba_exp \ sql \"にいくつかの.sqlファイルがあります。コードラインを「Open」と指定すると、エラー76が表示されますが、「c:\ Excelvba_exp \ sql \ *。sql」 'を入力するとエラー52が表示されます。使用する正しい構文に私を導いてください。この小さな点については、新しい質問が適切ではないかもしれません。 – skkakkar

関連する問題