2017-01-31 18 views

回答

0

@ erier的答案是非常好,将完成这项工作。

由于问题标记为Drupal 7,我想我会提交一个Drupal自定义模块方法,调整@ erier的答案并对其进行优化。

有关自定义模块的基础知识,您可以看到这个简单的示例。

function custom_module_form($form, &$form_state) { 
    $form['csv_upload'] = array(
    '#type' => 'file', 
    '#title' => t('Choose a file'), 
    '#title_display' => 'invisible', 
    '#size' => 22, 
    '#upload_validators' => array('file_clean_name' => array()), 
); 
    $form['upload'] = array(
    '#type' => 'submit', 
    '#value' => 'Upload', 
); 
} 

function custom_module_form_validate($form, &$form_state) { 
    $validators = array('file_validate_extensions' => array('csv')); 

    // Check for a new uploaded file. 
    $file = file_save_upload('csv_upload', $validators); 
    //$file = $form_state['values']['csv_upload']; 

    if (isset($file)) { 
    // File upload was attempted. 
    if ($file) { 
     // Put the temporary file in form_values so we can save it on submit. 
     $form_state['values']['csv_upload_file'] = $file; 
    } 
    else { 
     // File upload failed. 
     form_set_error('csv_upload', t('The file could not be uploaded.')); 
    } 
    } 
} 

function custom_module_submit($form, &$form_state) { 

    $file = $form_state['values']['csv_upload_file']; 
    $file->status = FILE_STATUS_PERMANENT; 
    $file->filename = str_replace(' ', '_', $file->filename); 
    file_save($file); 

    $csv_file = file_load($file->fid); 
    $file = fopen($csv_file->uri, "r"); 


    while(! feof($file)) 
     { 
     $customer = fgetcsv($file)); 
     db_insert('your_db_table') 
     ->fields(array(
      'column1' => $customer[0], 
      'column2' => $customer[1] 
     )) 
     ->execute(); 
     } 

    fclose($file); 

    drupal_set_message('CSV data added to the database'); 
} 

function file_clean_name($file) { 
    $file->filename = str_replace(' ', '_', $file->filename); 
} 

这是假设你的问题是关于一个数据库表。

如果你的意思是进入一个HTML表格,你可以$csv_file = file_load($file->fid);这样的后适应提交功能:

$headers = array('column 1', 'column 2'); 
$rows = array(); 

$file = fopen("contacts.csv","r"); 

while(! feof($file)) 
    { 
    $customer = fgetcsv($file)); 
    $rows[] = array($customer[0], $customer[1]); 
    } 

fclose($file); 

return theme('table', array('header' => $headers, 'rows' => $rows); 

或添加数据到数据库并显示到屏幕上没有第二个数据库适应两击中。

1

这是我想出来的 - 我不是PHP专家 - 它看起来并不漂亮 - 但它起作用!然后

$handle = fopen('/path/to/file/filename.csv', 'r'); 
$row = fgetcsv($handle); 

for ($e = 0; $row = fgetcsv($handle); $e++) { 
    $record = array(); 

    foreach ($row as $field) { 
     $record[] = $field; 
    } 

    db_insert('your_db_table') 
    ->fields(array(
     'column1' => $record[0], 
     'column2' => $record[1] 
    )) 
    ->execute(); 
} 

fclose($handle); 

表看起来就像这样:

column1|column2 
--------------- 
value1|value2 
value1|value2