1

I have a relatively complicated excel sheet in which columns start at A and end at BB and rows start at 5 and end at 203.

What I would like to do is tell MySQL that each column of data (with a header that I do not specify in the sheet) should start at row 5 and end at row 203 and specific exactly which columns I would like transferred. How might I do that?

Thanks for the help!

Edit: There is unrelated data below row 203 and I don't want that to be taken. There are also blank columns, so I need to avoid those.

1 Answer 1

1

First off, save your excel sheet as CSV.

Next. Create a blackhole table to read the data into:

DROP TABLE IF EXISTS `test`.`import_excel`;
CREATE TABLE  `test`.`import_excel` (
  `A` int(10) unsigned NOT NULL,
  `B` varchar(45) NOT NULL,
  `C` varchar(45) NOT NULL,
  `D` varchar(45) NOT NULL,
  `E` varchar(45) NOT NULL,
  .....
  `BB` varchar(45) NOT NULL
) ENGINE=BLACKHOLE DEFAULT CHARSET=latin1;

Create a simple counter table with just one row.

DROP TABLE IF EXISTS `test`.`counter`;
CREATE TABLE  `test`.`counter` (
  id int(10) unsigned NOT NULL PRIMARY KEY,
  `count` int(10) unsigned NOT NULL,
  `max_count` int(10) unsigned NOT NULL
) ENGINE=MEMORY DEFAULT CHARSET=latin1;

REPLACE INTO counter VALUES (1,0,(203-5));

Create a trigger on the blackhole table

DELIMITER $$

CREATE TRIGGER ai_import_excel_each AFTER INSERT ON import_excel FOR EACH ROW
BEGIN
  DECLARE rows_left integer;

  SELECT max_count - (`count` + 1)  INTO rows_left FROM counter WHERE id = 1;
  IF rows_left > 0 THEN BEGIN
    //count the row_number you're in.
    UPDATE counter SET `count` = `count` + 1 WHERE id = 1;

    //Interpret the data and insert it into the proper tables.
    //This is just an example
    INSERT INTO real_table (a,b,c) VALUES (new.a, new.b, new.c);
    INSERT INTO real_table2 (a,b,c) VALUES (NULLIF(new.d,''), new.e, new.c);
    //You can change the data in anyway you like.
  END; END IF;
END $$

DELIMITER ;

Finally import lines 5 to 203 into the import_excel table.

LOAD DATA INFILE 'c:/excel.csv' INTO TABLE import_excel 
  FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"'
  LINES TERMINATED BY '\r\n'
  IGNORE 4 LINES;

The first 4 lines will be ignored by the LOAD DATA INFILE the last lines will be stripped out by the trigger.

Sign up to request clarification or add additional context in comments.

1 Comment

Wow. I will try that out as soon as possible. Thanks for the thorough response.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.