javascript - 如何在 vue 组件中使用 Maatwebsite 导入 excel 文件?
问题描述
我已经这样做了,但那时我使用 laravel Blade 和 laravel 集体来保存表格。现在我正在使用 vue,这对我来说有点不同,而且对我来说太棘手了,因为我是 vuejs 的新手。我怎样才能做到这一点?我可以在 vue 组件中使用 laravel 集体,这样我的工作就会变得简单吗?感谢您的回答。这是我的代码。
Vue 组件
<div class="modal fade" id="exampleModal2" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title" id="exampleModalLabel">Import CSV</h4>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<form @submit.prevent="importRoom()">
<div class="modal-body">
<div class="form-group">
<label>Select CSV</label>
<input
v-on:change ="i dont have a method yet"
type="file"
name="template"
id="template"
class="form-control"
:class="{ 'is-invalid': form.errors.has('template') }"
/>
<has-error :form="form" field="bldg"></has-error>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-primary">Save changes</button>
</div>
</form>
</div>
</div>
</div>
我的路线
Route::post('/importRoom','RoomController@import');
控制器
public function import(Request $request){
if($request->hasFile('template')){
$path = $request->file('template')->getRealPath();
$data = \Excel::load($path)->get();
if($data->count() > 0){
$rows = $data->toArray();
foreach ($rows as $row) {
$inserts[]=[
'room_desc' => $row['room_desc'],
'bldg' => $row['bldg'],
];
}
}
$chuncked = array_chunk($inserts, 10);
if(empty($inserts)){
dd('Request data does not have any files to import.');
}
else {
foreach($chuncked as $inserts){
\DB::table('rooms')->insert($inserts);
}
dd('record inserted');
}
}
}
方法
importRoom(){
axios.post('/importRoom')
.then(()=>{
console.log('imported')
})
}
我的excel中只有两列要导入数据库。我对客户端真的很陌生,所以对我来说很难。谢谢帮忙。。
解决方案
onchange 您必须在 formData 中上传 excel 表
getExcelData(e) {
const formData = new FormData();
const file = e.target.files[0];
formData.append('file', file);
axios.post('url', formData)
.then(response => {
//Code to play with api response with excel data
})
.catch(error => {
//Catch errors
});
}
推荐阅读
- android - 通过意图打开邮件应用程序不会打开选择器
- java - 获取“java.sql.SQLException:Io 异常:网络适配器无法建立连接”错误
- gnuplot - 如何在 GPVAL_DATA_Y_MIN 处打印 X 值
- html - 如何根据 ui 中选择的输入值在服务器中获取输出值?
- ios - 金属 MTLGetWarningMode + 218 SIGABRT ABORT
- perl - 哈希上的“使用未初始化值”消息,但我认为密钥存在
- python - 从字典中找到路径最长的键
- neo4j - Neo4j:一个 CSV 列中的多个可能节点
- python - ImportError:没有名为 canard 的模块
- powershell - 在脚本中获取随机的“InputObject”验证错误